Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get child elements but none of their children?

Using MarkLogic but this is probably a generic XQuery question.

I have:

<library>
  <books>
    <book title="whatever">
      <publisher>Random</publisher>
      ....more children
    </book>
    <book title="another">
      <publisher>Simon</publisher>
      ....more children
    </book>
    ...
  </books>
</library>

I want to return all the [book] elements with their title attributes, but I do NOT want any of the children of book, e.g. [publisher]. How do I accomplish this in an orthodox and performant manner?

Correlated question: at times I may want to get some of the children, but not others, e.g. get all the book elements and their publisher child elements, but none of the other children.

Thanks.

like image 587
bethesdaboys Avatar asked Oct 21 '11 18:10

bethesdaboys


1 Answers

The XQuery (actually an XPath, which is a subset of XQuery) /library/books/book technically does what you want - it returns a set of book elements, and nothing else. Some APIs will return references to the book elements, and leave you to decide what you want to do with them, for example displaying their titles. However, many tools and APIs will copy these book elements together with the whole subtree rooted at the book, and in the case of a database, this is very often the result that will be transmitted over the network from the server to the client. In this case you don't want to select the existing book elements, you want to construct a new document containing a subset of the information in the book elements. To do this you can use element constructors in XQuery:

for $b in /library/books/book
return <book title="{$b/@title}"/>
like image 158
Michael Kay Avatar answered Jan 02 '23 23:01

Michael Kay