从 Java 文档中获取 xml 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4794196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:03:18  来源:igfitidea点击:

Getting xml string from Document in Java

javaxml

提问by Andry

I have a Java program aiming to consider an xml dom and write it into a string. I am using these packages: org.w3c.dom.*and javax.xml.parsers.*;

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

So I have DocumentBuilder, Document, Elementobjects...

所以我有DocumentBuilder, Document,Element对象...

Is there a way to get the string representing my xml dom in one call????

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

回答by Grammin

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 方法使字符串输出更漂亮,因此您可以将其取出。

回答by Tausif Baber

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

回答by Cezar Oliveira

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) 方法。

回答by ovdsrn

I'm also looking for a cheap and efficient way to serialize a DOM. Until now, I see only 2 options:

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

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

Maybe you can try the LSSerializer approach (but not in one call).

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