Dimple
Dimple

Reputation: 57

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?

Upvotes: 0

Views: 484

Answers (1)

spender
spender

Reputation: 120390

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

Upvotes: 1

Related Questions