java 如何将 dom4j 文档对象转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5575029/
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
how to convert dom4j document object to string
提问by Shamik
Just trying to find a way to convert a Dom4J Document content to String. It has a asXML()API which converts the content to a XML. In my case,I'm editing a non-xml DOM structure using Dom4J and trying to convert the content to String. I know its possible in case of w3c document.
只是想找到一种方法将 Dom4J 文档内容转换为字符串。它具有将内容转换为 XML的asXML()API。就我而言,我正在使用 Dom4J 编辑非 xml DOM 结构并尝试将内容转换为字符串。我知道在 w3c 文档的情况下它是可能的。
Any pointers will be appreciated.
任何指针将不胜感激。
Thanks
谢谢
回答by James
asXml() return String from Document object
asXml() 从 Document 对象返回字符串
String text = document.asXML()
回答by Mohamed Mansour
Why can't you just do:
你为什么不能这样做:
String result = dom.toXML().toString();
If you want to do it the long way, then you use a TransformerFactoryto transform the DOM to anything you want. First thing you do is wrap your Document in a DOMSource
如果您想长期这样做,那么您可以使用TransformerFactory将 DOM转换为您想要的任何内容。您要做的第一件事是将您的 Document 包装在DOMSource 中
DOMSource domSource = new DOMSource(document);
Prepare a StringWriterso we can route the stream to a String:
准备一个StringWriter以便我们可以将流路由到一个字符串:
StringWriter writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);
Prepare a TransformationFactoryso you can transform the DOM to the source provided:
准备一个TransformationFactory以便您可以将 DOM 转换为提供的源:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory .newTransformer();
transformer.transform(domSource, streamResult);
Finally, you get the String:
最后,你得到了String:
String result = writer.toString();
Hope that helped!
希望有所帮助!
回答by Theresa Forster
How can you have a non XML dom,
你怎么会有一个非 XML dom,
a Dom is in essence an XML document,
Dom 本质上是一个 XML 文档,
asXml() returns a string representation of the Dom , which is XML,
asXml() 返回 Dom 的字符串表示形式,即 XML,
if you need to pull just the text values then you can iterate through the dom and getValue() on elements but what you are asking for seems to be the xml string,
如果您只需要提取文本值,那么您可以遍历元素上的 dom 和 getValue(),但您要求的似乎是 xml 字符串,