I am trying to add an XML node to multiple parent nodes (which have the same name). But this is only an addition to the Last XML node and not to everyone.
XML input
<Record> <Emp> <ID>12</ID> <Name>ABC</Name> </Emp> <Emp> <ID>12</ID> <Name>ABC</Name> </Emp> </Record>
I want to add a Location element to each Emp node. My code is as follows:
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 get the output as follows:
<Record> <Emp> <ID>12</ID> <Name>ABC</Name> </Emp> <Emp> <ID>12</ID> <Name>ABC</Name> <Location>USA</Location> </Emp> </Record>
The Location element was not added to the first Emp node.
Note. After debugging, I can find that the element has been added even for the first Emp node. But in the saved XML file, I see this strange behavior.
source share