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

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.

+4
source share
1 answer

Your xNewChild is one new item. Just adding it to multiple nodes will only serialize to the last node. Such a change 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); 
+1
source

Source: https://habr.com/ru/post/1441384/


All Articles