Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xquery filter on attribute and element

Tags:

xpath

xquery

I have the following simple XML document:

<?xml version="1.0" encoding="UTF-8"?>
<cars>
    <car>
        <data attrib="Make">
            <text>Volvo</text>
        </data>
        <data attrib="Model">
            <text>855</text>
        </data>
    </car>
    <car>
        <data attrib="Make">
            <text>Volvo</text>
        </data>
        <data attrib="Model">
            <text>745</text>
        </data>
    </car>
    <car>
        <data attrib="Make">
            <text>Volvo</text>
        </data>
        <data attrib="Model">
            <text>V70R</text>
        </data>
    </car>
</cars>

And the following XPath:

/cars/car/data[(@attrib='Model') and (text='855')]

This returns the following result:

<data attrib="Model"><text>855</text></data>

I want the XPath to return the whole <car> block for the match.

So return data would be like this:

<cars>
    <car>
        <data attrib="Make">
            <text>Volvo</text>
        </data>
        <data attrib="Model">
            <text>855</text>
        </data>
    </car>
</cars>

How would I modify the XPath expression above to achieve this?

like image 731
general exception Avatar asked Jul 05 '12 08:07

general exception


People also ask

What is the significance of XQuery and XPath?

XQuery is an active programming language which is used to interact with XML data groups. XPath is an XML method language which is applied for node selection in XML dataset using queries.

What is XQuery used for?

What is XQuery For? XQuery was devised primarily as a query language for data stored in XML form. So its main role is to get information out of XML databases — this includes relational databases that store XML data, or that present an XML view of the data they hold.

What is XQuery HTML?

XQuery is About Querying XML XQuery is a language for finding and extracting elements and attributes from XML documents.


1 Answers

XPath returns whatever node you go up to - in your case you're going to data, so that's what you're getting back. If you want car instead, place your predicate after car.

/cars/car[data/@attrib='Model' and data/text='855']

Or, slightly shorter

/cars/car[data[@attrib='Model' and text='855']]

You can run it at this XMLPlayground.

XQuery to produce the desired output:

<cars>
  {/cars/car[data[@attrib='Model' and text='855']]}
</cars>
like image 136
Mitya Avatar answered Oct 01 '22 22:10

Mitya