1

I have an object of type

com.sun.org.apache.xerces.internal.dom.DeferredElementImpl

containing an XML root element and structure beneath.

How can I retrieve the XML contents as a string from this?

Note that method toString() is available, but this has been implemented in a very rudimentary way, only reporting strings like [root: null], hence only showing the root element name and not any further contents of this element.
In the javadoc this method is listed as "NON-DOM method for debugging convenience".

4

2 回答 2

5

我知道这有点晚了,但如果你还在寻找解决方案,试试这个:

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();

DOMSource source = new DOMSource(node);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result); 

nodeDeferredElementImpl 对象在哪里。DeferredElementImpl 实现了 Node 接口,因此您应该能够像使用任何其他 DOM 节点一样在其上使用转换器。

Oracle:“将 DOM 写为 XML 文件” com.sun.org.apache.xerces.internal.dom.DeferredElementImpl API

于 2013-08-14T20:20:38.077 回答
2

我使用这种方法从com.sun.org.apache.xerces.internal.dom.DeferredElementImpl

public static String getCharacterDataFromElement(Element e) throws Exception {
    String data = "";
    Node child = e.getFirstChild();
    if (child instanceof DeferredElementImpl) {
        DeferredElementImpl node = (DeferredElementImpl) child;
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer;
        transformer = tFactory.newTransformer();
        DOMSource source = new DOMSource(node);
        StreamResult result = new StreamResult(new StringWriter());
        transformer.transform(source, result);
        data = result.getWriter().toString();
    }
    return data;
}
于 2016-05-24T15:10:05.180 回答