How to add a new element below an existing element using an XML document

I have a Name element "Dispute" and you want to add a new name for the Records element 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> 

You must add a new item to the dispute.

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

Updated code: I tried to execute the following code, but get the error "The node link is not a 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); } 
+4
source share
3 answers

InsertAfter must call the parent node (in your case, "NonFuel").

 nonFuel.InsertAfter(xmlRecordNo, dispute); 

It may seem a bit confusing, but it reads like this: you are asking the parent node (nonFuel) to add a new node (xmlRecordNo) after the existing (dispute).

Here is a complete example:

 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); 
+8
source
 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"); 
+2
source

Use the "AppendChild" method - add as the last element.

0
source

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


All Articles