复制节点并更改属性的值

时间:2017-09-25 11:34:12

标签: c# xml xpath copy

我有以下XML文件。我想复制一个新的“测试”并更改测试的ID。怎么可能?

我已经可以复制节点了,遗憾的是没有在正确的位置(见图片),我也无法更改ID。 任何人都有我的解决方案吗?

在:
XML Now

在:
XML 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");

1 个答案:

答案 0 :(得分:0)

以下是使用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");