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);
}
When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".
An element can have one or more XML attributes . In the XML document in Figure 10.1 , the scene element is enclosed by the two tags <scene ...> and </scene> . It has an attribute number with value vii and two child elements, title and verse. Figure 10.2: The XML document in Figure 10.1 as a simplified DOM object.
XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument .
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);
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With