6

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();

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

or pass XPathConstants.NODESET, and assign evaluate to a NodeList. But coalescing is the easier thing to do.
Officially, in the XPath data model, text nodes are never split into pieces, so your query should return the result you expect. In practice, some XPath implementations that work on a DOM will fail to concatenate adjacent text nodes. One solution is to avoid use of text() (use string() on the element instead); another is to use setCoalescing() as suggested; a third is to use a conformant XPath processor, such as Saxon.
0

You could try changing the XPath expression to

"string(/rss/channel/title)"

and use return type STRING instead of NODE:

Node node = (Node) xPath.evaluate("string(/rss/channel/title)", doc,
                                  XPathConstants.STRING);

This way you are not selecting a text node, but rather the string value of the title element, which consists of the concatenation of all its descendant text nodes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.