Normally in PHP, I would just parse the old document and write to the new document while ignoring the unwanted elements.
A:
Have a look at the DOM methods, you can remove nodes.
http://htmlunit.sourceforge.net/apidocs/com/gargoylesoftware/htmlunit/html/DomNode.html
Ahmed Ashour
2010-09-25 07:49:56
Thank you Ahmed, I appreciate your comment. I already had a solution (see below) but your comment made me think that maybe I could find a simpler solution from the HtmlUnit API docs.
Jasper Ferrer
2010-09-26 14:35:51
Oops, my answer went above. Sorry, newbie here.
Jasper Ferrer
2010-09-26 14:56:59
A:
This was the first solution I came up with:
DocumentBuilder builder = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder();
StringReader reader = new StringReader( xml );
Document document = builder.parse( new InputSource(reader) );
XPathExpression expr = XPathFactory
.newInstance()
.newXPath()
.compile( ... );
Object result = expr.evaluate(document, XPathConstants.NODESET);
Element el = document.getDocumentElement();
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
el.removeChild( nodes.item(i) );
}
As you can see it's kinda long. Being a coder who strives for simplicity, I decided to take Ahmed's advice hoping I'll find a better solution and I came up with this:
List<?> elements = page.getByXPath( ... );
DomNode node = null;
for( Object o : elements ) {
node = (DomNode)o;
node.getParentNode().removeChild( node );
}
Please note these are just snippets, I omitted the imports and the XPath expressions but you get the idea.
Jasper Ferrer
2010-09-26 14:55:44