I am trying to add an XML node to multiple parent nodes(which have same name). But it is only adding to the Last node of the XML and not in all.
我试图将XML节点添加到多个父节点(具有相同的名称)。但它只是添加到XML的Last节点而不是全部。
input XML
<Record>
<Emp>
<ID>12</ID>
<Name>ABC</Name>
</Emp>
<Emp>
<ID>12</ID>
<Name>ABC</Name>
</Emp>
</Record>
I want to add the Location element to every Emp node. My code is as below:
我想将Location元素添加到每个Emp节点。我的代码如下:
XmlNodeList xNodeList = doc.SelectNodes("/Record/Emp");
XmlElement xNewChild = doc.CreateElement("Location");
xNewChild.InnerText = "USA";
foreach (XmlNode item in xNodeList)
{
item.AppendChild(xNewChild);
}
doc.Save(path);
but I am getting output like this:
但我得到这样的输出:
<Record>
<Emp>
<ID>12</ID>
<Name>ABC</Name>
</Emp>
<Emp>
<ID>12</ID>
<Name>ABC</Name>
<Location>USA</Location>
</Emp>
</Record>
The Location element has not been added to the first Emp node.
Location元素尚未添加到第一个Emp节点。
Note: After debugging, I am able to find that the element has been added even for the first Emp node. But, in the saved XML file I am seeing this strange behavior.
注意:调试后,我能够发现即使是第一个Emp节点也添加了元素。但是,在保存的XML文件中,我看到了这种奇怪的行为。
1 个解决方案
#1
1
Your xNewChild
is a single new element. Simply adding it to multiple nodes will only serialize to the last node. A change like this should work:
您的xNewChild是一个新元素。只需将其添加到多个节点,只会序列化到最后一个节点。这样的改变应该有效:
XmlNodeList xNodeList = doc.SelectNodes("/Record/Emp");
foreach (XmlNode item in xNodeList)
{
XmlElement xNewChild = doc.CreateElement("Location");
xNewChild.InnerText = "USA";
item.AppendChild(xNewChild);
}
doc.Save(path);
#1
1
Your xNewChild
is a single new element. Simply adding it to multiple nodes will only serialize to the last node. A change like this should work:
您的xNewChild是一个新元素。只需将其添加到多个节点,只会序列化到最后一个节点。这样的改变应该有效:
XmlNodeList xNodeList = doc.SelectNodes("/Record/Emp");
foreach (XmlNode item in xNodeList)
{
XmlElement xNewChild = doc.CreateElement("Location");
xNewChild.InnerText = "USA";
item.AppendChild(xNewChild);
}
doc.Save(path);