Link to home
Start Free TrialLog in
Avatar of TeknikDev
TeknikDevFlag for United States of America

asked on

Writing to XML file in C# WPF

Hi I need help updating an xml file in C# for two scenarios.

1) When a button is clicked on
2) when the form (program) exits.

I need to update the author, title and publisher values when these two actions take place.

Right now, the objects on the WPF form is binded to the xml file.  Thanks in advance.

Here's the xaml file:

[/<Canvas Canvas.Left="6" Canvas.Top="172" DataContext="{StaticResource BookData}" Height="79" Width="422">
                                <TextBox Background="{x:Null}" BorderBrush="{x:Null}" Canvas.Left="110" Canvas.Top="28" FontSize="12" FontWeight="Normal" IsReadOnly="True" Name="textBox2" Text="{Binding XPath=Book/Author}" Width="50" />

                                <TextBox Background="{x:Null}" BorderBrush="{x:Null}" Canvas.Left="110" Canvas.Top="52" FontSize="12" FontWeight="Normal" IsReadOnly="True" Name="textBox3" Text="{Binding XPath=Book/Title}" Width="50" />
                            

Open in new window


XML FILE
<?xml version='1.0'?>
<Data>
 <Book>
<title>The Test </title>
<author>Mike Williams </author>
<publisher>Angel Random </publisher>
 </Book>
</Data>
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Can you please show the complete XAML code and the code behind.

Thanks.
Avatar of TeknikDev

ASKER

 public void XMLUpdate(string val1, string val2, string val3)
        {

if(val1 == "1")
{
string xmlfilepath = @"C:\Users\tom\Desktop\Test.xml"; 
            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:\\Users\tom\Desktop\Test.xml");
            XmlNode root = doc.DocumentElement;
   XmlNode myNode = root.SelectSingleNode("Book:Author");
                myNode.Value = "Thomas"; 

            doc.Save(@"C:\\Users\tom\Desktop\Test.xml");

}

Open in new window



This isn't working - I get an error
Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function at this part of the code: XmlNode myNode = root.SelectSingleNode("Book:Author");

The logic is if I click on a button and call this method, where it says 1 then update value in xml file.

The method call is XMLUpdate("1", "0", "0") so this means only value 1 gets updated which is the author.
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I'm still getting the same error.
This worked! Thanks!
Did you change this @"Book:Author" to this @"Book/author" ?
Also does the actual XML that you are using is like the one you posted in the question?

By the way the solution I posted works on my machine.