Parsing XML

Hello everyone I want to add a new node as a parent node of old nodes in XML using C # .for example node has the following XMl file

<bookstore>
   <books>
      <author>
      </author>
   </books> 
</bookstore>

      

this is how now i want to add a new one like below

<bookstore>
 <newnode>
   <books>
      <author>
      </author>
   </books> 
 </newnode>
</bookstore>

      

Thanks to Advance Sekar

+1


source to share


3 answers


Try this: -



XmlDocument doc = new XmlDocument();
doc.Load("BookStore.xml");
XmlElement newNode = doc.CreateElement("newnode");
doc.DocumentElement.AppendChild(newNode);
newNode.AppendChild(doc.SelectSingleNode("/bookstore/books"));
doc.Save("BookStore.xml");

      

+2


source


We don't have VS, so I can't confirm it works, but something like this:



XmlDocument xd = new XmlDocument();
xd.Load("oldxmlfile.xml");
XmlNode oldNode = xd["nameOfRootNode"];
xd.RemoveAll();
XmlNode newParent = xd.CreateNode("nodename");
newParent.AppendChild(oldNode);
xd.AppendChild(newParent);
xd.Save("newXmlFile.xml");

      

0


source


You can clone the old node, add the clone and remove the original:

(edit; I forgot that AppendChild will move the node if it already exists ... no need to clone and delete ...)

XmlDocument doc = new XmlDocument();
// load the current xml
doc.LoadXml(xml);
// create a new "newnode" node and add it into the tree
XmlElement newnode = (XmlElement) doc.DocumentElement.AppendChild(doc.CreateElement("newnode"));
// locate the original "books" node and move it
newnode.AppendChild(doc.SelectSingleNode("/bookstore/books"));
// show the result
Console.WriteLine(doc.OuterXml);

      

0


source







All Articles