Удаление нежелательных узлов, использующих Xerces-C

StackOverflow https://stackoverflow.com/questions/9034969

  •  14-11-2019
  •  | 
  •  

Вопрос

Я использую Xerces 2.8.0.Я хочу удалить узлы комментариев из документа.

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++;
 }
.

Этот код работает нормально, если мой вход имеет следующий формат:

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

Но это не работает, если файл ввода имеет «красивый» формат такой:

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

Может кто-нибудь сказать мне, почему?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top