Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming Xml node

Tags:

c#

replace

xml

I try to rename any node starts with "NP" to "NP" in an XmlDocument. I only found this related questoin. based on the most up-voted answer I wrote:

 XmlNodeList npNodeList = PSbank.SelectNodes("//*[starts-with(name(), 'NP')]");

foreach (XmlNode npNode in npNodeList)
{

    // create new (renamed) Content node
    XmlNode newNode = PSbank.CreateElement("NP");

    // [if needed] copy existing Content children
    newNode.InnerXml = npNode.InnerXml;

    // replace existing Content node with newly renamed Content node
    npNode.ParentNode.InsertBefore(newNode, npNode);
    npNode.ParentNode.RemoveChild(npNode);
}

However, it seems it doesn't work in my case. When an NPX node contains other NPX nodes, the inner nodes are not replaced because the code manipulates XmlDocument and replaces the outer node with a new created node that contains the old innerXml.

Example Xml:

   <S>
     <NPC>
        <NP> A </NP>
        <NPA> B </NPA>
     </NPC>
     <NPD>
         C
     </NPD>
  </S>

I look for a more general and elegant answer for such a problem.

like image 234
Ahmad Avatar asked Aug 25 '16 13:08

Ahmad


1 Answers

I'd do this with LINQ to XML, it's a lot easier and cleaner. Firstly, it's generally a much nicer library, and secondly: XElement.Name is mutable.

var doc = XDocument.Parse(xml);  // or use XDocument.Load

foreach (var element in doc.Descendants())
{
    if (element.Name.LocalName.StartsWith("NP"))
    {
        element.Name = "NP";
    }
}

See this fiddle for a working demo.

like image 115
Charles Mager Avatar answered Oct 05 '22 15:10

Charles Mager