Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert XML node before specific node using c#

Tags:

c#

xml

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?

like image 223
SAK Avatar asked Jun 09 '10 09:06

SAK


People also ask

How do I select a specific node in XML?

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.

What is XML node in C#?

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.

What is the difference between node and element in XML?

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.


1 Answers

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);
like image 131
pierroz Avatar answered Sep 23 '22 23:09

pierroz