简体   繁体   English

从XML读取文本时如何忽略标签?

[英]How to ignore tags while reading text from XML?

I have an XML text containing nested tags. 我有一个包含嵌套标签的XML文本。 The structure is somewhat complicated. 结构有些复杂。 So i have used XPath queries to access a child node as described in this answer . 因此,我已经使用XPath查询访问此答案中描述的子节点。 However, now I have encountered text within that node which itself contains XML tag. 但是,现在我在该节点中遇到了本身包含XML标签的文本。 This method stops reading as soon as it encounters another XML tag. 一旦遇到另一个XML标记,此方法就会停止读取。

Following is the XML file: 以下是XML文件:

<x>
    <y>
        <z>
            This is a <tag>text</tag>
        </z>
    </y>
</x>

In the above XML, text inside <z> can be accessed by following method: 在上述XML中,可以通过以下方法访问<z>内的文本:

XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr= xpath.compile("/x/y/z/text()");
String text = (String) expr.evaluate(doc, XPathConstants.STRING);

But the value of text comes out to be "This is a" only. 但是,文本的值仅是“ This is a” I want the whole text to be displayed : This is a text 我希望显示整个文本: 这是一个文本

Simply use XPathExpression expr= xpath.compile("/x/y/z"); 只需使用XPathExpression expr= xpath.compile("/x/y/z"); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM