Search code examples
c#xmlxpathxpathdocument

Editing a tag in XpathDocument in C#


I have XpathDocument object which has content like

<MainTag>
   <XYZTag>
      <Tag>
       <CTag ID="ABS"/>
      </Tag>
     </XYZTag>
     <ABCTag>
       <CTag ID="ABS"/>
      </ABCTag>
      <FGHTag>
       <CTag ID="ABS"/>
      </FGHTag>
</MainTag>

I want to remove

<Tag> </Tag> 

to make it look like

<MainTag>
   <XYZTag>

       <CTag ID="ABS"/>

     </XYZTag>
     <ABCTag>
       <CTag ID="ABS"/>
      </ABCTag>
      <FGHTag>
       <CTag ID="ABS"/>
      </FGHTag>
</MainTag>

I tried assign innerXML to outerXML, apparently not allowed. Myriad of online solution also not work. Is it possible to have this change in XPathDocument?


Solution

  • Does it have to be XPathDocument. You can do this easily using XmlDocument. Here's one example.

    var xml = @"
    <MainTag>
          <Tag>
           <CTag ID='ABS'/>
          </Tag>
    </MainTag>";
    
    var doc = new XmlDocument();
    doc.LoadXml(xml);
    var tagNode = doc.SelectSingleNode("//Tag");
    
    var ctagNode = tagNode.FirstChild;
    tagNode.ParentNode.ReplaceChild(ctagNode, tagNode);