M
M
MaxLich2017-06-04 16:32:13
Java
MaxLich, 2017-06-04 16:32:13

Why doesn't inserting a comment node after every node with a specific name in an XML document work?

I wrote this code, and it does not work as it should:

NodeList ourTags = root.getElementsByTagName(tagName);
            Node commentTag = document.createComment(comment);
            for (int i = 0; i < ourTags.getLength(); i++) {
                if (ourTags.item(i).getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) ourTags.item(i);

                    Node n = element.getParentNode().insertBefore(commentTag, element);
                    System.out.println(n);
                }
            }

It is necessary that after each tag with the name tagName a tag with a comment is inserted. But at me it is inserted only after the last. I can't figure out why. If you manually bypass all several elements of the NodeList and insert a comment tag before each, then the comment tag is also inserted only before the last tag from the list that I accessed. Before the first, for example, does not interpose. If you manually insert only before the first found tag (they are searched by name), then everything is inserted normally. But I need to have a comment tag before every tag with that name.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaxLich, 2017-06-04
@MaxLich

I found the error myself. It was necessary to create it immediately when inserting a new node. And he created one in advance, and tried to put it everywhere.
That is, in the code there should be such a line:
instead of the one that is.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question