Itzik984
Itzik984

Reputation: 16764

JAVA Ignore commented out xml tags

While i'm parsing an XML document, i get commented out code as a node (which is a bad idea to begin with), i wan't to know when we have a commented out node/bulk and not to parse it.

This is the code that parses the XML elements:

private static boolean updateXML(File file, Document doc, NodeList nodeList) 
{
    if(nodeList==null)
        return false;

    boolean somethingChanged = false;
    for(int i=0;i<nodeList.getLength();i++)
    {
        if(nodeList.item(i).hasChildNodes())
        {
            somethingChanged |= updateXML(file, doc, nodeList.item(i).getChildNodes());
        }
        else
        { ... }
    }
}

and when i debug it, i can see the commented out part is brought up as one complete node.

How can i ignore these comments?

Upvotes: 3

Views: 2401

Answers (2)

Sachin Gupta
Sachin Gupta

Reputation: 8358

Use this:

Node node = nodeList.item(i);
if(node.getNodeType() == Node.COMMENT_NODE) {
    continue;
} else {
    //do something
}

Upvotes: 6

Rima
Rima

Reputation: 545

Using DocumentBuilderFactory you can set to completely ignore the comments in the file.

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setIgnoringComments(true);

Now parse any file:

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(filePath);

The document won't contain any comments.

Upvotes: 3

Related Questions