Maestro13
Maestro13

Reputation: 3696

com.sun.org.apache.xerces.internal.dom.DeferredElementImpl convert to string

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".

Upvotes: 1

Views: 3119

Answers (2)

Mise
Mise

Reputation: 3567

I use this method for get String from 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;
}

Upvotes: 2

shela
shela

Reputation: 121

I know this is a little late, but if you're still looking for a solution, try this:

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

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

where node is the DeferredElementImpl object. DeferredElementImpl implements the Node interface, so you should be able to use a transformer on it like with any other DOM node.

Oracle: "Writing Out a DOM as an XML File" com.sun.org.apache.xerces.internal.dom.DeferredElementImpl API

Upvotes: 5

Related Questions