您将使用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(); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)