如何将子节点添加到现有XML [英] How to add child node to existing XML
本文介绍了如何将子节点添加到现有XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个XML文件如下:
I have one XML file as follow:
<Employees>
<Employee>
<EmpId>10</EmpId>
</Employee>
<Employee>
<EmpId>11</EmpId>
</Employee>
</Employees>
使用C#我只想制作如下文件:
Using C# I just want to make this file as follow:
<Employees>
<Employee>
<EmpId>10</EmpId>
<EName>AA</EName>
</Employee>
<Employee>
<EmpId>11</EmpId>
<EName>BB</EName>
</Employee>
</Employees>
感谢你。
Thank U.
推荐答案
您显示的XML文件非常小而且简单,因此您可以使用最简单的方法:使用可用的XML解析器读入DOM结构中的整个文件,System.Xml.XmlDataDocument
:
http://msdn.microsoft.com/en-us/library/system.xml.xmldocument%28v=vs.110%29.aspx [ ^ ]。
您将文件解析为DOM,将子项添加到DOM,将其保存到文件中。
您标记为C#.2.0,但您没有告诉我们您是否可以使用.NET Framework 3.5或更高版本。如果可以,你还有另外一个选择:
你可以用类System.Xml.Linq做类似的事情,如果你愿意的话。 XDocument
,支持LINQ to XML编程:
http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument%28v=vs.110%29.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/vstudio/bb387098%28v=vs.100%29.aspx [ ^ ]。
-SA
The XML files you show are very small and simple, so you could use probably the simplest way: read the whole file in a DOM structure by using available XML parser into the DOM,System.Xml.XmlDataDocument
:
http://msdn.microsoft.com/en-us/library/system.xml.xmldocument%28v=vs.110%29.aspx[^].
You parse the file into DOM, add children to DOM, save it to file.
You tag says C#.2.0, but you did not tell us if you can use .NET Framework 3.5 or later. If you can, you have another option:
You can do something similar, if you prefer, with the classSystem.Xml.Linq.XDocument
, supporting LINQ to XML programming:
http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/vstudio/bb387098%28v=vs.100%29.aspx[^].
—SA
XmlDocument doc = new XmlDocument();
doc.Load("d:\\test\\book.xml");
XmlElement elmRoot = doc.DocumentElement;
foreach (XmlNode n in doc.DocumentElement)
{
XmlElement newtitle = doc.CreateElement("EName");
newtitle.InnerText = "SomeText";
n.AppendChild(newtitle);
}
doc.Save("d:\\book.xml");
这篇关于如何将子节点添加到现有XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文