Change the node names in an XML file using C#

后端 未结 8 1881
南笙
南笙 2020-12-09 17:51

I have a huge bunch of XML files with the following structure:


  someContent
  someType
&         


        
8条回答
  •  心在旅途
    2020-12-09 18:11

    (1.) The [XmlElement / XmlNode].Name property is read-only.

    (2.) The XML structure used in the question is crude and could be improved.

    (3.) Regardless, here is a code solution to the given question:

    String sampleXml =
      ""+
        ""+
          "someContent"+
          "someType"+
        ""+
        ""+
          "someContent"+
          "someType"+
        ""+
        ""+
          "someContent"+
          "someType"+
        ""+
      "";
    
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(sampleXml);
    
    XmlNodeList stuffNodeList = xmlDoc.SelectNodes("//*[starts-with(name(), 'Stuff')]");
    
    foreach (XmlNode stuffNode in stuffNodeList)
    {
        // get existing 'Content' node
        XmlNode contentNode = stuffNode.SelectSingleNode("Content");
    
        // create new (renamed) Content node
        XmlNode newNode = xmlDoc.CreateElement(contentNode.Name + stuffNode.Name);
    
        // [if needed] copy existing Content children
        //newNode.InnerXml = stuffNode.InnerXml;
    
        // replace existing Content node with newly renamed Content node
        stuffNode.InsertBefore(newNode, contentNode);
        stuffNode.RemoveChild(contentNode);
    }
    
    //xmlDoc.Save
    

    PS: I came here looking for a nicer way of renaming a node/element; I'm still looking.

提交回复
热议问题