简体   繁体   中英

Export DOM Document as XML with userData as Attribute

I am handling a Document object with data, some of the nodes have userData associated to them (using setUserData(<key>, <value>, <handler>) ). I want to save a copy of the Document to XML, with exporting the userData values as attributes.

Transformer

This is the way I know to output XML:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(<Document>);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);

But there I cannot find a way to hook in at a method where both the old and the new Node objects exist – the only place I could find while digging into Transformer was a class DOM2TO that translates the nodes into eg. SAX calls to startElement(...) , but I cannot change anything here without copyPasting the whole code around it.

UserDataHandler

My second approach was to use a UserDataHandler to attach to the Node together with the userData. That handler has to provide a method handle(short operation, String key, Object data, Node src, Node dst) that is called eg. when the Node is cloned. So it would be possible to write a UserDataHandler that checks the src Node for userData and add it as an Attribute to dst and then simply cloning the Document before writing the XML from the clone. Unfortunately , handle(...) is getting called at a stage when the dst Node clone is not finished: When src has attributes, dst will point to the same AttributeMap instance at that time. Thus, the whole process is worthless, because the added attributes would also get added to the original Document, and I do not want to do that.

Got it solved – I have to user a UserDataHandler that works at NODE_IMPORTED : Then the handle(...) method is called with a completely cloned dst node.

This is not a nice solution though, as cloning (hrm, importing ) the Document doubles the needed space.

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