Changing the root name of an XML element

I have XML stored in a string variable:

<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList> 

Here I want to change the XML tag <ItemMasterList> to <Masterlist> . How can i do this?

+6
c #
source share
5 answers

System.Xml.XmlDocument , and its associated classes in the same namespace, will prove invaluable here.

 XmlDocument doc = new XmlDocument(); doc.LoadXml(yourString); XmlDocument docNew = new XmlDocument(); XmlElement newRoot = docNew.CreateElement("MasterList"); docNew.AppendChild(newRoot); newRoot.InnerXml = doc.DocumentElement.InnerXml; String xml = docNew.OuterXml; 
+10
source share

You can use LINQ to XML to parse an XML string, create a new root, and add children and attributes of the original root to the new root:

 XDocument doc = XDocument.Parse("<ItemMasterList>...</ItemMasterList>"); XDocument result = new XDocument( new XElement("Masterlist", doc.Root.Attributes(), doc.Root.Nodes())); 
+6
source share

I know that I'm a little late, but just have to add this answer, since no one seems to know about it.

 XDocument doc = XDocument.Parse("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>"); doc.Root.Name = "MasterList"; 

Which returns the following:

 <MasterList> <ItemMaster> <fpartno>xxx</fpartno> <frev>000</frev> <fac>Default</fac> </ItemMaster> </MasterList> 
+6
source share

Using the XmlDocument method, you can do this as follows (and keep the tree intact):

 XmlDocument oldDoc = new XmlDocument(); oldDoc.LoadXml("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>"); XmlNode node = oldDoc.SelectSingleNode("ItemMasterList"); XmlDocument newDoc = new XmlDocument(); XmlElement ele = newDoc.CreateElement("MasterList"); ele.InnerXml = node.InnerXml; 

If you now use ele.OuterXml , it returns: (you just need a string, otherwise use XmlDocument.AppendChild(ele) and you can use the XmlDocument object a bit more)

 <MasterList> <ItemMaster> <fpartno>xxx</fpartno> <frev>000</frev> <fac>Default</fac> </ItemMaster> </MasterList> 
0
source share

As Will A pointed out, we can do just that, but for the case where InnerXml is OuterXml, the following solution will be worked out:

 // Create a new Xml doc object with root node as "NewRootNode" and // copy the inner content from old doc object using the LastChild. XmlDocument docNew = new XmlDocument(); XmlElement newRoot = docNew.CreateElement("NewRootNode"); docNew.AppendChild(newRoot); // The below line solves the InnerXml equals the OuterXml Problem newRoot.InnerXml = oldDoc.LastChild.InnerXml; string xmlText = docNew.OuterXml; 
0
source share

All Articles