4

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.

1 Answer 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:

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.