/** * Create a NodeModel from an XML file. * * @param removeComments whether to remove all comment nodes (recursively) from the tree before * processing * @param removePIs whether to remove all processing instruction nodes (recursively from the tree * before processing */ public static NodeModel parse(File f, boolean removeComments, boolean removePIs) throws SAXException, IOException, ParserConfigurationException { DocumentBuilder builder = getDocumentBuilderFactory().newDocumentBuilder(); if (errorHandler != null) builder.setErrorHandler(errorHandler); Document doc = builder.parse(f); if (removeComments) { removeComments(doc); } if (removePIs) { removePIs(doc); } mergeAdjacentText(doc); return wrap(doc); }
/** * Recursively removes all comment nodes from the subtree. * * @see #simplify */ public static void removeComments(Node node) { NodeList children = node.getChildNodes(); int i = 0; int len = children.getLength(); while (i < len) { Node child = children.item(i); if (child.hasChildNodes()) { removeComments(child); i++; } else { if (child.getNodeType() == Node.COMMENT_NODE) { node.removeChild(child); len--; } else { i++; } } } }