Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get html from a org.w3c.dom.Node in java?

I've build a method which extracts data from an html document using the xpath components of saxon-he. I'm using w3c dom object model for this.

I already created a method which returns the text-value, similar like the text value method from jsoup (jsoupElement.text()):

    protected String getNodeValue(Node node) {
    NodeList childNodes = node.getChildNodes();
    for (int x = 0; x < childNodes.getLength(); x++) {
        Node data = childNodes.item(x);
        if (data.getNodeType() == Node.TEXT_NODE)
            return data.getNodeValue();
    }
    return "";
 }

This works fine but i now i need the underlying html of a selected node (with jsoup it would be jsoupElement.html()). Using the w3c dom object model i have org.w3c.dom.Node. How can i get the html from a org.w3c.dom.Node as String? I couldn't find anything regarding this in the documentation.

Just for clarification: I need the inner html (with or without the node element/tag) as String. Similar like http://api.jquery.com/html/ or http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#html--

like image 286
whitenexx Avatar asked Apr 12 '26 15:04

whitenexx


1 Answers

To serialize a W3C DOM Node's child nodes to HTML with Saxon you can use a default Transformer where you set the output method to html:

public static String getInnerHTML(Node node) throws TransformerConfigurationException, TransformerException
{
    StringWriter sw = new StringWriter();
    Result result = new StreamResult(sw);
    TransformerFactory factory = new net.sf.saxon.TransformerFactoryImpl();
    Transformer proc = factory.newTransformer();
    proc.setOutputProperty(OutputKeys.METHOD, "html");
    for (int i = 0; i < node.getChildNodes().getLength(); i++)
    {
        proc.transform(new DOMSource(node.getChildNodes().item(i)), result);
    }
    return sw.toString();
}

But as said, this is a serialization of the tree, the original XML or HTML is not stored in a DOM tree or Saxon's tree model, there is no way to access it.

like image 183
Martin Honnen Avatar answered Apr 14 '26 11:04

Martin Honnen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!