简体   繁体   English

Xpath查找给定子项具有最大值的元素

[英]Xpath to find the element with the maximum value for a given child

Here is the XML: 这是XML:

<root>
  <ACTS>
    <ACT>Play</ACT>
    <A>
      <Day>1</Day>
      <time>Fri Feb 28 13:21:42 IST 2014</time>
    </A>
    <A>
      <Day>2</Day>
      <time>Fri Feb 28 13:21:43 IST 2014</time>
    </A>    
  </ACTS>
  <ACTS>
    <ACT>Study</ACT>
    <A>
      <Day>1</Day>
      <time>Fri Feb 28 13:21:42 IST 2014</time>
    </A>
    <A>
      <Day>2</Day>
      <time>Fri Feb 28 13:21:43 IST 2014</time>
    </A> 
    <A>
      <Day>3</Day>
      <time>Fri Feb 28 13:21:43 IST 2014</time>
    </A>   
  </ACTS>
</root>

How can I find the element A and its children for ACT = 'Study' for which the value of Day is maximum? 如何找到Day =最大值的ACT = 'Study'的元素A及其子元素? Here is the Java program: 这是Java程序:

String xp = "//ACTS[ACT='Study']/A[not(Day < //ACTS[ACT='Study']/A/Day)]";
XPathExpression expr = xpath.compile(xp);
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
if (null != nl && null != nl.item(0)) {
    String abc = nl.item(0).getChildNodes().item(0).getNodeValue();
    System.out.println(abc);
}

Note: With this XPath I am able to get the maximum value for Day by 注意:通过此XPath,我能够获得Day的最大值

NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
if (null != nl && null != nl.item(0)) {
    maxAttemptNumber = nl.item(0).getTextContent();
} 

but need help in getting element A and its children. 但需要帮助以获取元素A及其子元素。

If you're using Java, then you can use XQuery as easily as XPath 2.0 or XPath 1.0 (eg with the Saxon library). 如果您使用Java,则可以像XPath 2.0或XPath 1.0一样轻松使用XQuery(例如,使用Saxon库)。 The answer is then 答案是

(for $a in //ACTS[ACT="Study"]/A
order by number($a/Day))[last()] 

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

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