psobhan
psobhan

Reputation: 635

How to add new element below existing element using xml Document

I have an element Name "Dispute" and want to add new element name "Records" below the element.
Eg: The current XML is in this format

<NonFuel>
    <Desc>Non-Fuel</Desc>
    <Description>
    </Description>
    <Quantity/>
    <Amount/>
    <Additional/>
    <Dispute>0</Dispute>
</NonFuel>

Need to add new element under dispute.

<NonFuel>
    <Desc>Non-Fuel</Desc>
    <Description>
    </Description>
    <Quantity/>
    <Amount/>
    <Additional/>
    <Dispute>0</Dispute>
    <Records>01920</Records>
</NonFuel>

Updated Code:
Tried doing the following Code but getting error "The reference node is not child of this node":

XmlDocument xmlDoc=new XmlDocument()
xmlDoc.LoadXml(recordDetails);
XmlNodeList disputes = xmlDoc.GetElementsByTagName(disputeTagName);
XmlNode root = xmlDoc.DocumentElement;
foreach (XmlNode disputeTag in disputes)
{
    XmlElement xmlRecordNo = xmlDoc.CreateElement("RecordNo");
    xmlRecordNo.InnerText = Guid.NewGuid().ToString();
    root.InsertAfter(xmlRecordNo, disputeTag);
}

Upvotes: 10

Views: 60571

Answers (3)

Navin Pandit
Navin Pandit

Reputation: 179

Use 'AppendChild' method - to add as last element.

Upvotes: 0

Paolo Falabella
Paolo Falabella

Reputation: 25834

InsertAfter must be called on the parent node (in your case "NonFuel").

nonFuel.InsertAfter(xmlRecordNo, dispute);

It may look a little confusing but it reads this way: you are asking the parent node (nonFuel) to add a new node (xmlRecordNo) after an existing one (dispute).

A complete example is here:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(@"<NonFuel><Desc>Non-Fuel</Desc><Description></Description><Quantity/><Amount/><Additional/><Dispute>0</Dispute></NonFuel>");

XmlNode nonFuel = xmlDoc.SelectSingleNode("//NonFuel");
XmlNode dispute = xmlDoc.SelectSingleNode("//Dispute");


XmlNode xmlRecordNo=  xmlDoc.CreateNode(XmlNodeType.Element, "Records", null);
xmlRecordNo.InnerText = Guid.NewGuid().ToString();
nonFuel.InsertAfter(xmlRecordNo, dispute);

Upvotes: 12

Martin Honnen
Martin Honnen

Reputation: 167446

XmlDocument doc = new XmlDocument();
doc.Load("input.xml");

XmlElement records = doc.CreateElement("Records");
records.InnerText = Guid.NewGuid().ToString();
doc.DocumentElement.AppendChild(records);

doc.Save("output.xml"); // if you want to overwrite the input use doc.Save("input.xml");

Upvotes: 6

Related Questions