Удаление нежелательных узлов, использующих Xerces-C
Вопрос
Я использую 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.
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.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 callingList-item(i)
withi
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.