使用 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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜有两件事在你的循环中没有按预期工作。
如果从父节点中删除子节点,其余元素的位置也会发生变化。因此,在这种情况下,您不应增加
i
以避免跳过下一个元素。此外,由于子元素的数量发生了变化,计数变量的值实际上不再有效。这不是什么大问题,因为您在使用
node
之前会检查它,但您可能会使用i
调用List-item(i)
超出范围。此外,您可以保存一些调用,这会提高性能,特别是对于有很多注释的大文件。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.