[英]Copy Node and change Value of an Attribute
I have the following XML File. 我有以下XML文件。 I want to copy a new "Test" and change the ID of the Test.
我想复制一个新的“测试”并更改测试的ID。 How is it possible?
这怎么可能?
I already can copy the nodes, unfortunately not on the correct position (see images) and I also can´t change the ID. 我已经可以复制节点了,不幸的是,复制节点的位置不正确(参见图片),并且我也无法更改ID。 Anyone have a solution for me?
有人对我有解决方案吗?
Before: 之前:
After: 后:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Before.xml");
XmlNode Set = xmldoc.DocumentElement;
string strXmlQuery = "/Toolings/Testing/Test1";
XmlNode NodeToCopy = Set.SelectSingleNode(strXmlQuery);
XmlNode NewNode = NodeToCopy.CloneNode(true);
NodeToCopy.AppendChild(NewNode);
Set.InsertAfter(NewNode, Set.LastChild);
XPathNavigator navigator = xmldoc.CreateNavigator();
navigator.MoveToRoot();
navigator.MoveToFirstChild();
navigator.MoveToFirstChild();
navigator.MoveToFirstChild();
navigator.MoveToFirstChild();
navigator.SetValue("5678");
xmldoc.Save(After.xml");
Here is an example using System.Xml.Linq.XDocument
which is a much easier API than XmlDocument
: 这是一个使用
System.Xml.Linq.XDocument
的示例,它比XmlDocument
容易得多的API:
//You can also use Load(), this is just so I didn't have to make a file
XDocument doc = XDocument.Parse("<Toolings><Testing><Test><ID>1234</ID></Test></Testing></Toolings>");
//Grab the first Test node (change the predicate if you have other search criteria)
var elTest = doc.Descendants().First(d => d.Name == "Test");
//Copy the node, only necessary if you don't know the structure at design time
XElement el = new XElement(elTest);
el.Element("ID").Value = "5678";
//inject new node
elTest.AddAfterSelf(el);
doc.Save("After.xml");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.