【问题标题】:Get full xml text from Node instance从 Node 实例获取完整的 xml 文本
【发布时间】:2011-11-10 02:45:43
【问题描述】:

我已经用这样的代码阅读了 Java 中的 XML 文件:

File file = new File("file.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);

NodeList nodeLst = doc.getElementsByTagName("record");

for (int i = 0; i < nodeLst.getLength(); i++) {
     Node node = nodeLst.item(i);
...
}

那么,如何从节点实例中获取完整的 xml 内容? (包括所有标签、属性等)

谢谢。

【问题讨论】:

  • “获取完整的 xml 内容”是什么意思?您希望返回什么类型的对象?一个字符串?还有什么?
  • 完整的 xml 内容将在 file.xml 中,还是我错过了重点?否则尝试stackoverflow.com/questions/35785/xml-serialization-in-javaxstream.codehaus.org/tutorial.html
  • @PaulGrime,你的意思是,我必须用 XML 序列化器序列化“节点”实例吗?
  • @JimGarrison,“获取完整的 xml 内容”我的意思是下一个(例如):data数据data

标签: java xml


【解决方案1】:

从 stackoverflow 中查看另一个 answer

您将使用 DOMSource(而不是 StreamSource),并在构造函数中传递您的节点。

然后就可以把节点转成String了。

快速示例:

public class NodeToString {
    public static void main(String[] args) throws TransformerException, ParserConfigurationException, SAXException, IOException {
        // just to get access to a Node
        String fakeXml = "<!-- Document comment -->\n    <aaa>\n\n<bbb/>    \n<ccc/></aaa>";
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(fakeXml)));
        Node node = doc.getDocumentElement();

        // test the method
        System.out.println(node2String(node));
    }

    static String node2String(Node node) throws TransformerFactoryConfigurationError, TransformerException {
        // you may prefer to use single instances of Transformer, and
        // StringWriter rather than create each time. That would be up to your
        // judgement and whether your app is single threaded etc
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), xmlOutput);
        return xmlOutput.getWriter().toString();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 2017-03-29
    • 2017-07-31
    • 2013-06-19
    • 2020-10-05
    • 2015-11-22
    相关资源
    最近更新 更多