Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify XML existing content in C#

Tags:

Purpose: I plan to Create a XML file with XmlTextWriter and Modify/Update some Existing Content with XmlNode SelectSingleNode(), node.ChildNode[?].InnerText = someting, etc.

After I created the XML file with XmlTextWriter as below.

XmlTextWriter textWriter = new XmlTextWriter("D:\\learning\\cs\\myTest.xml", System.Text.Encoding.UTF8);

I practiced the code below. But failed to save my XML file.

XmlDocument doc = new XmlDocument();
doc.Load("D:\\learning\\cs\\myTest.xml");

XmlNode root = doc.DocumentElement;
XmlNode myNode;

myNode= root.SelectSingleNode("descendant::books");

....

textWriter.Close();

doc.Save("D:\\learning\\cs\\myTest.xml");  

I found it is not good to produce like my way. Is there any suggestion about it? I am not clear about the concepts and usage of both XmlTextWriter and XmlNode in the same project. Thank you for reading and replies.

like image 593
Nano HE Avatar asked Mar 31 '10 08:03

Nano HE


People also ask

How do you edit the contents of XML?

XML files can also be edited using your computer's notepad program and even with certain word processing and spreadsheet programs. However, XML editors are considered advantageous because they are able to validate your code and ensure you remain within a valid XML structure.

Which class is used in C for writing an XML file?

This example writes the object from a class to an XML file using the XmlSerializer class.


1 Answers

Well, If you want to update a node in XML, the XmlDocument is fine - you needn't use XmlTextWriter.

XmlDocument doc = new XmlDocument();
doc.Load("D:\\build.xml");
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::books");
myNode.Value = "blabla";
doc.Save("D:\\build.xml");
like image 167
jujusharp Avatar answered Oct 22 '22 12:10

jujusharp