开发者

Convert an org.w3c.dom.Node into a String

开发者 https://www.devze.com 2022-12-19 07:22 出处:网络
Sorry I\'m a Java/XML newbie - and can\'t seem to figure this one out. It seems it\'s po开发者_C百科ssible to convert a Document object to a string. However, I want to convert a Node object into a str

Sorry I'm a Java/XML newbie - and can't seem to figure this one out. It seems it's po开发者_C百科ssible to convert a Document object to a string. However, I want to convert a Node object into a string. I am using org.ccil.cowan.tagsoup Parser for my purpose.

I'm retrieving the Node by something like...

 parser = new org.ccil.cowan.tagsoup.Parser() 

 parser.setFeature(namespaceaware, false)

 Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
 DOMResult domResult = new DOMResult(); 

 transformer.transform(new SAXSource(parser, new InputSource(in)), domResult);
 Node n = domResult.getNode();      

 // I'm interested in the first child, so...
 Node myNode = n.getChildNodes().item(0);

 // convert myNode to string..
 // what to do here?

The answer may be obvious, but I can't seem to figure out from the core Java libraries how to achieve this. Any help is much appreciated!


You can use a Transformer (error handling and optional factory configuration omitted for clarity):

Node node = ...;
StringWriter writer = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(node), new StreamResult(writer));
String xml = writer.toString();
// Use xml ...


String getNodeString(Node node) {
    try {
        StringWriter writer = new StringWriter();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(new DOMSource(node), new StreamResult(writer));
        String output = writer.toString();
        return output.substring(output.indexOf("?>") + 2);//remove <?xml version="1.0" encoding="UTF-8"?>
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return node.getTextContent();
}


This is way to convert Node to html

public static String getInnerHTML(Node node) throws TransformerConfigurationException, TransformerException
{
    StringWriter sw = new StringWriter();
    Result result = new StreamResult(sw);
    TransformerFactory factory = TransformerFactory.newInstance();
    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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号