简体   繁体   中英

Add element to multiple parent nodes at a specific position in xml file

I need to add a new element "Location" to every parent node "Emp" after the element "ID".

<Record>
 <Emp>
  <ID>12</ID>
  <Name>ABC</Name>
 </Emp>
 <Emp>
  <ID>12</ID>
  <Name>ABC</Name>
 </Emp>
</Record>

I followed example and the steps in below answer by Erik Philips

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

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

Instead of this

item.AppendChild(xNewChild);

i added new statement

item.InsertAfter(xNewChild, doc.SelectSingleNode("Emp//ID"));

This inserts the new element right after Emp node starts and not after ID.

<Record>
 <Emp>
  <Location>USA</Location>
  <ID>12</ID>
  <Name>ABC</Name>
 </Emp>
 <Emp>
  <Location>USA</Location>
  <ID>12</ID>      
  <Name>ABC</Name>
 </Emp>
</Record>

Can anyone suggest me where am i going wrong?

XmlDocument is an old API and has been superceded by XDocument , which provides a somewhat more pleasurable experience when dealing with XML.

Using XDocument you can:

var doc = XDocument.Parse(xmlString); //acquire your XDocument (perhaps by other means)

var targetElements = doc.XPathSelectElements("//Record/Emp/ID");

foreach (var element in targetElements)
{
    var locationElement = new XElement("Location");
    locationElement.Add("USA");
    element.AddAfterSelf(locationElement);
}

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