import org.apache.xerces.parsers.DOMParser;
import org.xml.sax.SAXException;
import org.w3c.dom.*;
import org.apache.xerces.dom.*;
import java.io.IOException;
import org.w3c.dom.events.*;
import org.apache.xerces.dom.events.*;
class MainClass{
public static void main(String args[]) throws SAXException, IOException {
new DemoEventsModule();
}
}
public class DemoEventsModule implements EventListener {
public DemoEventsModule() throws SAXException, IOException {
DOMParser parser = new DOMParser();
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion",false);
parser.parse("games.xml");
Document doc = parser.getDocument();
Node node = doc.getDocumentElement().getFirstChild();
Node clone = node.cloneNode(true);
((DocumentImpl) doc).addEventListener("DOMNodeRemoved", this, false);
EventTarget evTarget = (EventTarget) doc;
evTarget.addEventListener("DOMNodeInserted", this, false);
doc.getDocumentElement().removeChild(node);
doc.getDocumentElement().appendChild(clone);
}
public void handleEvent(Event ev) {
if (ev.getType().equals(MutationEventImpl.DOM_NODE_REMOVED)) {
Node node = (Node) ev.getTarget();
Node parentNode = node.getParentNode();
System.out.println("Node " + node.getNodeName()+ " was removed from " + parentNode.getNodeName());
}
if (ev.getType().equals(MutationEventImpl.DOM_NODE_INSERTED)) {
Node node = (Node) ev.getTarget();
Node parentNode = node.getParentNode();
System.out.println("Node " + node.getNodeName()+ " was inserted as a child of "+ parentNode.getNodeName());
}
}
}
//game.xml
/*
<?xml version="1.0"?>
<games>
<game genre="shooter">XML Invaders</game>
<game genre="rpg">A Node in the XPath</game>
<game genre="action">XPath Racers</game>
</games>
*/
|