TeknikDev
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:
XML FILE
<?xml version='1.0'?>
<Data>
<Book>
<title>The Test </title>
<author>Mike Williams </author>
<publisher>Angel Random </publisher>
</Book>
</Data>
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" />
XML FILE
<?xml version='1.0'?>
<Data>
<Book>
<title>The Test </title>
<author>Mike Williams </author>
<publisher>Angel Random </publisher>
</Book>
</Data>
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");
}
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("Boo
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I'm still getting the same error.
ASKER
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.
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.
OK
Thanks.