This is my XML file
<employee>
<name ref="a1" type="xxx"></name>
<name ref="a2" type="yyy"></name>
<name ref="a3" type="zzz"></name>
</employee>
Using C#, I need to insert this node
<name ref="b2" type="aaa"></name>
between the "a2" and "a3" nodes. Any pointer how to sort this out?
To find nodes in an XML file you can use XPath expressions. Method XmlNode. SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.
XmlNode is the base class in the . NET implementation of the DOM. It supports XPath selections and provides editing capabilities. The XmlDocument class extends XmlNode and represents an XML document. You can use XmlDocument to load and save XML data.
An Element is part of the formal definition of a well-formed XML document, whereas a node is defined as part of the Document Object Model for processing XML documents.
use the insertAfter method:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(yourFile);
XmlNode xElt = xDoc.SelectSingleNode("//name[@ref=\"a2\"]");
XmlElement xNewChild = xDoc.CreateElement("name");
xNewChild.SetAttribute("ref", "b2");
xNewChild.SetAttribute("type", "aaa");
xDoc.DocumentElement.InsertAfter(xNewChild, xElt);
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