java中如何使用XPath查找带有CDATA标签的节点值 [英] how to use XPath to find the node value with CDATA tag in java

查看:27
本文介绍了java中如何使用XPath查找带有CDATA标签的节点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用XPath解析了rss xml数据,数据为

<频道><标题><![CDATA[体育新闻]]></频道></rss>

我想使用 xpath "/rss/channel/title/text()" 获取文本 "sports news" ,但结果不是我想要的,真正的结果是 "\r\n",那么如何找到我想要的结果.

代码如下:

<前>文档文档 = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);XPathFactory xpathFactory = XPathFactory.newInstance();XPath xPath = xpathFactory.newXPath();Node node = (Node) xPath.evaluate("/rss/channel/title/text()", doc,XPathConstants.NODE);String title = node.getNodeValue();

解决方案

尝试调用 setCoalescing(true) 在您的 DocumentBuilderFactory 上,这会将所有 CDATA/文本节点折叠为单个节点.

I used XPath to parse rss xml data, and the data is

<rss version="2.0">
  <channel>
    <title>
      <![CDATA[sports news]]>
    </title>
  </channel>
</rss>  

I want to get the text "sports news" using xpath "/rss/channel/title/text()" ,but the result is not what I want ,the real result is "\r\n",so how to found the result I want.

the code is below:

    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xPath = xpathFactory.newXPath();
    Node node = (Node) xPath.evaluate("/rss/channel/title/text()", doc,XPathConstants.NODE);
    String title = node.getNodeValue();

解决方案

Try calling setCoalescing(true) on your DocumentBuilderFactory and this will collapse all CDATA/text nodes into single nodes.

这篇关于java中如何使用XPath查找带有CDATA标签的节点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆