如何将dom4j文档对象转换为字符串

发布于 2024-10-30 21:03:13 字数 174 浏览 5 评论 0原文

只是想找到一种将 Dom4J 文档内容转换为字符串的方法。它有一个 asXML() API,可将内容转换为 XML。就我而言,我正在使用 Dom4J 编辑非 xml DOM 结构并尝试将内容转换为字符串。我知道在 w3c 文档中这是可能的。

任何指示将不胜感激。

谢谢

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.

Any pointers will be appreciated.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

人│生佛魔见 2024-11-06 21:03:13

asXml() 从 Document 对象返回字符串

String text = document.asXML()

asXml() return String from Document object

String text = document.asXML()
咋地 2024-11-06 21:03:13

为什么你不能这样做:

String result = dom.toXML().toString();

如果你想长期这样做,那么你可以使用 TransformerFactory 将 DOM 转换为你想要的任何内容。您要做的第一件事是将文档包装在 DOMSource 中,

DOMSource domSource = new DOMSource(document);

准备一个 StringWriter,以便我们可以将流路由到字符串:

StringWriter writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);

准备一个 TransformationFactory,以便您可以将 DOM 转换为提供的源:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory .newTransformer();
transformer.transform(domSource, streamResult);

最后,您得到 String

String result = writer.toString();

希望有所帮助!

Why can't you just do:

String result = dom.toXML().toString();

If you want to do it the long way, then you use a TransformerFactory to transform the DOM to anything you want. First thing you do is wrap your Document in a DOMSource

DOMSource domSource = new DOMSource(document);

Prepare a StringWriter so we can route the stream to a String:

StringWriter writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);

Prepare a TransformationFactory so you can transform the DOM to the source provided:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory .newTransformer();
transformer.transform(domSource, streamResult);

Finally, you get the String:

String result = writer.toString();

Hope that helped!

佼人 2024-11-06 21:03:13

你怎么能有一个非 XML dom,

Dom 本质上是一个 XML 文档,

asXml() 返回 Dom 的字符串表示形式,即 XML,

如果你只需要提取文本值,那么你可以迭代 dom 并getValue() 在元素上,但你要求的似乎是 xml 字符串,

How can you have a non XML dom,

a Dom is in essence an XML document,

asXml() returns a string representation of the Dom , which is 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,

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文