简体   繁体   中英

How to retrieve parent node with child node that matching certain criteria using xquery?

I'm trying to get partial data from my xml file,
The source file is like this:

<Odds>
  <Match ID="101" Time="A">
    <Event type="Home">
      <Score="1"/>
    </Event>
    <Event type="Away">
      <Score="2"/>
    </Event>
  </Match>
  <Match ID="102" Time="B">
    <Event type="Home">
      <Score="1"/>
    </Event>
    <Event type="Away">
      <Score="2"/>
    </Event>
  </Match>
</Odds>

I want to get the Odds, Match, Event, Score tags where Event type match "Home" only.
That is, the result is as below:

<Odds>
  <Match ID="101" Time="A">
    <Event type="Home">
      <Score="1"/>
    </Event>
  </Match>
  <Match ID="102" Time="B">
    <Event type="Home">
      <Score="1"/>
    </Event>
  </Match>
</Odds>

I'm fresh to XML, have read some books.
Tried to add criteria in WHERE of xquery and RETURN the parent node.
But the result always returns the Match with full child nodes.
That is, there is no difference between the result and the original one.
Is there any good way to do to get rid of those events that the type is not Home?
Thanks for the help!

If your XQuery processor support XQuery update, you can write the following:

  copy $odds-proj := $odds
  modify delete node $odds-proj//Event[@type = "Away"]
  return $odds-proj

You can try this example live at http://28.io/sandbox/index#QzdH/9PIwe11cJnVVZSqhpBdJkQ=

If you are working with a huge file, I recommend you do use the following query:

for $match in $odds/Match
return <Match>
{$match/attribute()}
{$match/element()[@type = "Home"]}
</Match>

You can see this example live at http://28.io/sandbox/index#dwQcDXHxyl69BijJq6o5Mx8Fvrk= Additionally, if you are looking to stream a large XML documents with Zorba, I would recommend you to check out the tutorial at http://www.zorba-xquery.com/html/entry/2012/05/31/XML_Streaming

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