修改C#中的XML现有内容

Nan*_* HE 20 c# xml xmlnode xmltextwriter

目的:我计划使用XmlTextWriter创建XML文件,并使用XmlNode SelectSingleNode(),node.ChildNode [?]修改/更新一些现有内容.InnerText = someting等.

用XmlTextWriter创建XML文件后,如下所示.

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

我练习下面的代码.但未能保存我的XML文件.

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

XmlNode root = doc.DocumentElement;
XmlNode myNode;

myNode= root.SelectSingleNode("descendant::books");
Run Code Online (Sandbox Code Playgroud)

....

textWriter.Close();

doc.Save("D:\\learning\\cs\\myTest.xml");  
Run Code Online (Sandbox Code Playgroud)

我发现按照我的方式生产是不好的.有什么建议吗?我不清楚同一个项目中XmlTextWriter和XmlNode的概念和用法.感谢您阅读和回复.

小智 31

好吧,如果你想用XML更新节点,那XmlDocument很好 - 你不需要使用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");
Run Code Online (Sandbox Code Playgroud)


Kas*_*han 23

如果您使用的是框架3.5,请使用LINQ to xml

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");
Run Code Online (Sandbox Code Playgroud)


小智 7

形成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();           
Run Code Online (Sandbox Code Playgroud)

要编辑Xml节点,请使用以下代码

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"); 
Run Code Online (Sandbox Code Playgroud)

试试这个.这是C#代码.


Han*_*ing 6

XmlTextWriter通常用于生成(不更新)XML内容.将xml文件加载到XmlDocument中时,不需要单独的编写器.

只需更新您选择的节点和.Save()即XmlDocument.