简体   繁体   中英

xPath.evaluate only returns a single node

I have the following XML structure:

...
...
  <CON>
    <LANGUAGES>
      <LANGUAGE>Deutsch</LANGUAGE> 
      <LANGUAGE>English</LANGUAGE> 
    </LANGUAGES>
  <CON>
  ...
  ...

Using my code below, I'm trying to retrieve the languages but when I try to print the length of the node list, it only returns 1.

XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList)xPath.evaluate("/CU_DATA/CU/CON/LANGUAGES", document, XPathConstants.NODESET);                                  

System.out.println(nl.getLength()); 
// Output: 1

How can I get the two languages?

How can I get the two languages?

By asking for the LANGUAGE elements instead of LANGUAGES - after all, there is only one LANGUAGES element. So something like this:

NodeList nl = (NodeList)xPath.evaluate("/CU_DATA/CU/CON/LANGUAGES/LANGUAGE",
                                       document, XPathConstants.NODESET);   

Alternatively, find the LANGUAGES element as you're currently doing, and then just fetch all the child nodes.

try :

NodeList nl = (NodeList)xPath.evaluate("/CU_DATA/CU/CON/LANGUAGES//LANGUAGE", document, XPathConstants.NODESET);               

or

NodeList nl = (NodeList)xPath.evaluate("/CU_DATA/CU/CON/LANGUAGES//*", document, XPathConstants.NODESET);               

/ is used to separate the nodes where as // returns all the nodes recursively

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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