Quantcast
Channel: Rename Root Node in XML
Viewing all articles
Browse latest Browse all 6

Rename Root Node in XML

$
0
0

Hey Ajay,

hopefully the code below should serve your purpose; not sure how well it performs, but definitely does the job.

 

using System;using System.Xml;using System.Xml.XPath;namespace QuickApp
{class Program
    {staticvoid Main(string[] args)
        {new Program();
            Console.WriteLine("Done");
            Console.ReadKey();
        }private Program()
        {
            test();
        }privatevoid test()
        {conststring xmldata = "<group>\r\n<a id='a'> t1 </a>\r\n<b id='b'> t2</b>\r\n</group>";
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(xmldata);
            ReplaceNode(xml, "/*/*[local-name()='b']", "c");
            Console.WriteLine(xml.OuterXml);
        }privatevoid ReplaceNode(XmlDocument xml, string xpath, string name)
        {
            XmlNode node = xml.CreateNode(XmlNodeType.Element, name, xml.NamespaceURI);
            XPathNavigator navi = xml.CreateNavigator();
            XPathNodeIterator iterator = navi.Select(xpath);while (iterator.MoveNext())
            {if (iterator.Current.IsNode)
                {
                    ((IHasXmlNode)iterator.Current).GetNode().Rename(name);
                }
            }
        }
    }staticclass XmlNodeExtensions
    {publicstaticvoid Rename(this XmlNode xmlNode, string name)
        {
            xmlNode.Rename(name, xmlNode.NamespaceURI);
        }publicstaticvoid Rename(this XmlNode xmlNode, string name, string namespaceUri)
        {
            XmlNode newNode = xmlNode.OwnerDocument.CreateNode(xmlNode.NodeType, name, namespaceUri);while (xmlNode.Attributes.Count>0) //can't use HasAttributes as that's not available to all xmlNode types 
            {
                newNode.Attributes.Append(xmlNode.Attributes[0]);
            }while (xmlNode.HasChildNodes)
            {
                newNode.AppendChild(xmlNode.ChildNodes[0]);
            }
            xmlNode.ReplaceMe(newNode);
        }publicstaticvoid ReplaceMe(this XmlNode oldNode, XmlNode newNode)
        {
            XmlNode parent = oldNode.ParentNode;
            parent.ReplaceChild(newNode, oldNode);//or//parent.InsertBefore(newNode, oldNode);//parent.RemoveChild(oldNode);
        }
    }
}


Also there's a typo in your xml - your closing tag for element b is a close fora.  Just pointing it out in case that's in your data & not just a typo.

Hope that helps.

JB


Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>