5

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.

1
  • Provide some xml examples, thanks. Commented Aug 25, 2016 at 14:01

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.