[英]Getting xml string from Document in Java
I have a Java program aiming to consider an xml dom and write it into a string. 我有一个Java程序,旨在考虑一个xml dom并将其写入一个字符串。 I am using these packages:
org.w3c.dom.*
and javax.xml.parsers.*;
我正在使用这些包:
org.w3c.dom.*
和javax.xml.parsers.*;
So I have DocumentBuilder
, Document
, Element
objects... 所以我有
DocumentBuilder
, Document
, Element
对象......
Is there a way to get the string representing my xml dom in one call???? 有没有办法在一次调用中获取代表我的xml dom的字符串????
Its not one call but: 它不是一个电话,而是:
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();
The setOutputProperty method makes the string output prettier so you can take it out. setOutputProperty方法使字符串输出更漂亮,因此您可以将其取出。
String xmlString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
The method org.apache.axis.utils.XMLUtils.PrettyDocumentToString(Document) have a problem that includes white spaces in the tag values. 方法org.apache.axis.utils.XMLUtils.PrettyDocumentToString(Document)的问题包括标记值中的空格。
A solution is use the method org.apache.axis.utils.XMLUtils.DocumentToString(Document). 解决方案是使用方法org.apache.axis.utils.XMLUtils.DocumentToString(Document)。
I'm also looking for a cheap and efficient way to serialize a DOM. 我也在寻找一种廉价而有效的序列化DOM的方法。 Until now, I see only 2 options:
到目前为止,我只看到两个选项:
Maybe you can try the LSSerializer approach (but not in one call). 也许您可以尝试LSSerializer方法(但不能在一次调用中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.