Hi,
The first method fails because there is a bug in the AbstractElement.accept(Visitor) method
IMHO accept should not assume that the visitor will not change the structure of the element, and it caches the element & attribute counts for performmance.
Is there any reason why a visitor should not modify the content?. I will start a separate post regarding this
The second method failes because you are attempting to remove the node from the document, not the parent node.
If you use
n.getParent().remove(n),
or better still
n.detach()
Then it works
> -----Original Message-----
> From: [EMAIL PROTECTED]
> [
mailto:[EMAIL PROTECTED]] On Behalf Of> [EMAIL PROTECTED]
> Sent: Wednesday 16 June 2004 13:57
> To: [EMAIL PROTECTED]
> Subject: [dom4j-user] Removing Nodes
>
>
> Hi!
>
> I try to remove all <DIV>s from a Document but this seems to
> be somewhat
> tricky :-) I'd prefer to use a Visitor; the code below throws an
> NullPointerException. The second approach simply doesn't work:
>
> import java.io.FileReader;
> import java.util.List;
> import java.util.Iterator;
>
> import org.cyberneko.html.parsers.SAXParser;
> import org.dom4j.Document;
> import org.dom4j.Element;
> import org.dom4j.Node;
> import org.dom4j.VisitorSupport;
> import org.dom4j.io.SAXReader;
>
> public class Test
> {
> static class KillDivs extends VisitorSupport
> {
> public void visit( Element e )
> {
> if (e.getName().equalsIgnoreCase("div"))
> {
> e.getParent().remove(e);
> return;
> }
> }
> }
>
> public static void main(String[] args)
> {
> try
> {
> SAXReader reader = new SAXReader(new
> SAXParser());
> Document doc = reader.read(new
> FileReader("test.html"));
> // doc.accept(new KillDivs());
> List divs = doc.selectNodes("//DIV");
> for (Iterator<Node> iter =
> divs.iterator(); iter.hasNext(); )
> {
> Node n = iter.next();
> if(n.getName().equalsIgnoreCase("div"))
> {
> doc.remove(n);
> }
> }
> String s = doc.asXML();
> System.out.println(s.indexOf("<DIV>"));
> }
> catch (Exception e)
> {
> System.err.println("->"+e);
> }
> }
>
> }
>
>
> -------------------------------------------------------
> This SF.Net email is sponsored by The 2004 JavaOne(SM) Conference
> Learn from the experts at JavaOne(SM), Sun's Worldwide Java Developer
> Conference, June 28 - July 1 at the Moscone Center in San
> Francisco, CA
> REGISTER AND SAVE!
http://java.sun.com/javaone/sf Priority> Code NWMGYKND
> _______________________________________________
> dom4j-user mailing list
> [EMAIL PROTECTED]
>
https://lists.sourceforge.net/lists/listinfo/dom4j-user>