xquery to find value of a child attribute by giving values for one attibute at same level and parent and one of

StackOverflow https://stackoverflow.com/questions/22341528

  •  13-06-2023
  •  | 
  •  

Question

I need to find value for a child attribute by giving values for one attibute at the same level and its parent at highere level.
Another requirement is
find value for a child attribute for which another attribute at same level with maximum value and given value for parent at higher level

Here is my 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>
`   

and the rquirement is to find the value for time attribute by giving values as Day=3 and ACT =Study

find time where ACT =Study and Day= maximum value under ACT=Study

I have tried the same with xpath and ended up with a mess (not able to retrieve values from Nodelist).

someone please guide me xquery and its usage in java for this..

which is best in this situation xquery or xpath.

Was it helpful?

Solution

let $x :=

<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>

XQuery -

let $maxDay := max($x//ACTS[ACT="Study"]/A/Day)
for $y in $x//ACTS[ACT/text()="Study"]/A[Day/text()=$maxDay]/time
 return $y

XPath -

//ACTS[ACT/text()="Study"]/A[Day/text()=max(//ACTS[ACT="Study"]/A/Day)]/time

You said - "someone please guide me xquery and its usage in java for this.. "

For this please refer following posts -

  1. How to read XML using XPath in Java

  2. Parsing XML with XPath in Java

Assuming your Java code is right, I think, your XPath expression put you in the mess. BTW, above links would guide you for the correctness of Java code.

You asked - "which is best in this situation xquery or xpath. "

Google for "Difference between XQuery and XPath", and you will get the answer.

HTH :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top