简体   繁体   中英

Add an XML node to multiple parent nodes(which have same name)

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.

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:

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.

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.

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:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM