removing unwanted nodes using xerces-c

1.8k views Asked by At

i am using xerces 2.8.0. I want to delete the comment nodes from the document.

List = root->getChildNodes();
int count = List->getLength();
int i = 0;
while (i < count)
{
    DOMNode* node = List->item(i);
    if(node != 0 && node->getNodeType() == DOMNode::COMMENT_NODE)
    {
         cout<<"comment node found"<<endl;
         root->removeChild(node);
    }
    i++;
 }

this code works fine if my input has the following format:

 <?xml version="1.0"?>
 <root><!-- comment --><node1>txt</node1></root>

But it doesn't work if the input file has the "pretty" format like this:

 <?xml version="1.0"?>
 <root>
      <!-- comment -->
      <node1>txt</node1>
 </root>

Can anyone tell me why?

1

There are 1 answers

3
Clemens On BEST ANSWER

I guess two things are not working as expected in your loop.

  1. If you remove a child node from the parent the positions of the remaining elements are also changing. So you shouldn't increase i in this case to avoid to skip over the next element.

  2. Also the value of the count variable is actually no longer valid as the number of child elements has changed. This is not a big deal because you are checking node before you are using it but you are possibly calling List-item(i) with i out of range. In addition you can save some calls and this would increase the performance especially for large files if they have a lot of comments.