从Node实例获取完整的xml文本

从Node实例获取完整的xml文本,第1张

从Node实例获取完整的xml文本

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

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

快速样本

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5616243.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存