Search code examples
c++xml-parsinglibxml2

Delete comments from xml file while parsing it using libxml


Following is the XML file with one of its node(i.e. <date>) being commented.

<?xml version="1.0"?>
<story>
  <info>
    <author>Abc Xyz</author>
    <!--<date>June 2, 2017</date> -->
    <keyword>example keyword</keyword>
  </info>
</story>

What I want is to remove that commented line/node completely from the XML file using libxml library and it should look as below:

<?xml version="1.0"?>
<story>
  <info>
    <author>Abc Xyz</author>
    <keyword>example keyword</keyword>
  </info>
</story>

I also referred the libxml documentation but that didn't helped me much with the "comment/s" in XML file.


Solution

  • I tried in a different way and it worked. Looks like using xmlreader for modifying the xml will not help much, instead I did xmlReadMemory(), then while parsing did following check:

    if(node->type == XML_COMMENT_NODE){ //node is of type xmlNodePtr
        xmlUnlinkNode(node);
        xmlFreeNode(node);
    }
    

    And finally xmlDocDumpFormatMemory() to store the modified xml in xmlbuffer.