Purpose: I plan to Create a XML file with XmlTextWriter and Modify/Update some Existing Content with XmlNode SelectSingleNode(), node.ChildNode[?].InnerText = someting, etc.
Using LINQ to xml if you are using framework 3.5
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
xmlw.WriteStartDocument();
xmlw.WriteStartElement("examtimes");
xmlw.WriteStartElement("Starttime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Changetime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Endtime");
xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
xmlw.WriteEndElement();
xmlw.WriteEndElement();
xmlw.WriteEndDocument();
xmlw.Close();
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\WINDOWS\Temp\exm.xml");
XmlNode root = doc.DocumentElement["Starttime"];
root.FirstChild.InnerText = "First";
XmlNode root1 = doc.DocumentElement["Changetime"];
root1.FirstChild.InnerText = "Second";
doc.Save(@"C:\WINDOWS\Temp\exm.xml");
Try this. It's C# code.
The XmlTextWriter is usually used for generating (not updating) XML content. When you load the xml file into an XmlDocument, you don't need a separate writer.
Just update the node you have selected and .Save() that XmlDocument.
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");