将org.w3c.dom.Node转换为String

时间:2010-02-08 16:21:04

标签: java xml-serialization

抱歉,我是一名Java / XML新手 - 似乎无法想象这一点。似乎可以将Document对象转换为字符串。但是,我想将Node对象转换为字符串。我正在使用org.ccil.cowan.tagsoup Parser。

我正在通过像...这样的东西检索节点。

 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?

答案可能很明显,但我似乎无法从核心Java库中弄清楚如何实现这一目标。非常感谢任何帮助!

3 个答案:

答案 0 :(得分:46)

您可以使用Transformer(为清晰起见,省略了错误处理和可选的出厂配置):

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

答案 1 :(得分:4)

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();
}

答案 2 :(得分:0)

这是将Node转换为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();
}