简体   繁体   English

使用userData作为属性将DOM文档导出为XML

[英]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>) ). 我正在处理带有数据的Document对象,某些节点具有与之关联的userData(使用setUserData(<key>, <value>, <handler>) )。 I want to save a copy of the Document to XML, with exporting the userData values as attributes. 我想将Document的副本保存为XML,并导出userData值作为属性。

Transformer 变压器

This is the way I know to output XML: 这是我知道的输出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. 但是,在那里我找不到找到旧的和新的Node对象都存在的方法的方法–挖掘Transformer ,我唯一能找到的地方就是DOM2TO类, DOM2TO将节点转换为例如。 SAX calls to startElement(...) , but I cannot change anything here without copyPasting the whole code around it. SAX调用startElement(...) ,但是在这里我不能在不复制粘贴整个代码的情况下更改任何内容。

UserDataHandler UserDataHandler

My second approach was to use a UserDataHandler to attach to the Node together with the userData. 我的第二种方法是使用UserDataHandler与userData一起附加到Node。 That handler has to provide a method handle(short operation, String key, Object data, Node src, Node dst) that is called eg. 该处理程序必须提供一个称为例如的方法handle(short operation, String key, Object data, Node src, Node dst) 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. 因此,可以编写一个UserDataHandler来检查src节点中的userData并将其作为dst的属性添加,然后在从克隆写入XML之前简单地克隆Document。 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. 不幸的是handle(...)dst Node克隆未完成的阶段被调用:当src具有属性时, dst当时将指向同一AttributeMap实例。 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. 解决了–我必须使用在NODE_IMPORTED上运行的UserDataHandler:然后使用完全克隆的dst节点调用handle(...)方法。

This is not a nice solution though, as cloning (hrm, importing ) the Document doubles the needed space. 但是,这不是一个很好的解决方案,因为克隆(hrm, 导入 )文档会使所需的空间增加一倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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