tags:

views:

254

answers:

3
+1  Q: 

XML Parsing

Hi All i want add the new node as parent node of the old nodes in XML using C#.for example node have the following XMl file

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

like that now i want add the new like below

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

Thanks in Advance Sekar

A: 

Don't have VS here so can't confirm that this 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");
A: 

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

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

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);
Marc Gravell
+1  A: 

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");
AnthonyWJones