質問

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