繁体   English   中英

从Java中的Document获取xml字符串

[英]Getting xml string from Document in Java

我有一个Java程序,旨在考虑一个xml dom并将其写入一个字符串。 我正在使用这些包: org.w3c.dom.*javax.xml.parsers.*;

所以我有DocumentBuilderDocumentElement对象......

有没有办法在一次调用中获取代表我的xml dom的字符串????

它不是一个电话,而是:

TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.METHOD, "xml");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));

StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc.getDocumentElement());

trans.transform(source, result);
String xmlString = sw.toString();

setOutputProperty方法使字符串输出更漂亮,因此您可以将其取出。

String xmlString =  org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);

方法org.apache.axis.utils.XMLUtils.PrettyDocumentToString(Document)的问题包括标记值中的空格。

解决方案是使用方法org.apache.axis.utils.XMLUtils.DocumentToString(Document)。

我也在寻找一种廉价而有效的序列化DOM的方法。 到目前为止,我只看到两个选项:

  • JAXP转换(类似于Grammin)
  • LSSerializer就像这里: http ://xerces.apache.org/xerces2-j/faq-dom.html#faq-3。

也许您可以尝试LSSerializer方法(但不能在一次调用中)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM