将 org.w3c.dom.Node 转换为字符串

2022-09-01 08:15:37

对不起,我是一个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库中找出如何实现这一目标。任何帮助都非常感谢!


答案 1

您可以使用转换器(为清楚起见,省略了错误处理和可选的工厂配置):

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

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

推荐