java中如何使用Dom4j获取XML的节点内容
我有一个 XML 文件,如下所示:
<description>
<text>blahblah</text>
<code>code</code>
<text>blah</text>
</description>
我已导航到节点 description
,并且我想读取完整内容,包括
等。
我使用了 getText()
,但它返回了空字符串。
我使用了 getStringValue()
,但它过滤了所有
。
我使用了 asXML()
,结果很接近,但结果包含我不想要的
。
有没有一种方法可以获取元素的 XML 内容?
I have a XML file like:
<description>
<text>blahblah</text>
<code>code</code>
<text>blah</text>
</description>
I've navigated to the node description
, and I want to read the full content including the <text>
and so on.
I've used the getText()
, but it returned empty string.
I've used the getStringValue()
, but it filtered all <text>
.
I've used the asXML()
, the result is close, but the result contains <description>
which I don't want.
Is there a method to get the XML content of a element?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
像这样的事情:
请注意,如果元素本身具有文本内容,则不会返回文本内容,只会返回子节点。
Something like this:
Note that if the element has text content itself, this won't return the text content, only the child nodes.
假设
document
是org.dom4j.Document
的实例,那么Assume that
document
is and instance oforg.dom4j.Document
, then您应该考虑使用 XPath: http://www.ibm.com/ developerworks/library/x-javaxpathapi/index.html
You should look at using XPath: http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html
只是想添加到 qwerky 接受的答案中:
还能够解析纯文本元素的内容(即它不包含嵌套的 xml):
所以我在方法的开头添加了以下内容:
Just want to add to the accepted answer by qwerky:
To ALSO be able to parse the contents of text only elements (ie it doesn't contain nested xml):
So I added the following at the start of the method: