从Node实例获取完整的xml文本 [英] Get full xml text from Node instance

查看:204
本文介绍了从Node实例获取完整的xml文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Java读取了这个代码的XML文件:

I have read XML file in Java with such code:

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内容从节点实例? (包括所有标签,属性等。)

So, how I can get full xml content from node instance? (including all tags, attributes etc.)

谢谢。

推荐答案

查看其他回答来自stackoverflow。

Check out this other answer from stackoverflow.

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

You would use a DOMSource (instead of the StreamSource), and pass your node in the constructor.

然后您可以将节点转换为字符串。

Then you can transform the node into a 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();
    }
}

这篇关于从Node实例获取完整的xml文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆