AmKh
AmKh

Reputation: 21

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.

Upvotes: 1

Views: 932

Answers (2)

AmKh
AmKh

Reputation: 21

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.

Upvotes: 1

x squared
x squared

Reputation: 3354

You can use NodeType() while parsing the xml and check for each node if it’s a comment (8 means comment, see here: http://xmlsoft.org/xmlreader.html#Extracting) and then remove it with xmlUnlinkNode() and xmlFreeNode().

Upvotes: 0

Related Questions