简体   繁体   中英

Java : how to know when a XML Document has been modified

Is there some clean method to know when some content of a DOM Document has been modified, without having to recurse into its nodes and hashing tons of data ?

I would avoid to generate the full XML String (see @AdriaanKoster' response)

Using a listener or whatever "clever", as @mthmulders pointed it out, seems to be the right way.

I found an interesting SO post here , maybe is it THE answer ?

Any tip ?

Thanks

You could check whether your Document also is an instance of EventTarget . If so, you can use the addEventListener method to handle any events. For example, if the event being handled is a MutationEvent , you might get information about the modification to the document.

I did this once by serializing the Document to String and taking its hashcode. Not an extremely expensive operation I think. It goes something like this:

private int calculateHashCode(org.w3c.dom.Document document) {
    try { 
        DOMSource source = new DOMSource(document);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty("indent","no");
        transformer.transform(domSource, result);        
        return stringWriter.toString().hashCode();
    }
    catch(TransformerException e) {
        return -1;
    }
}

I am returning -1 in case of an exception because I don't want to burden the calling code with exception handling whilst determining the hashCode. It means that changes in documents which cannot be transformed successfully will not be detected correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM