0

I have a xml file

<category>
    <type name="SWEATERS">
        <product id =1>
            <itemNumber>1</itemNumber>
            <name>ProductA2</name>
            <price>345</price>
        </product>
        <product id=2>
            <itemNumber>4</itemNumber>
            <name>Product Test </name>
            <price>456</price>
        </product>
    </type>
</category>

I used the xquery

$xml->xpath('//category/type/product[@id=1]');

When i used this xquery iam getting only the name and price.How i can get the type name 'SWEATERS' along with name and price

4 Answers 4

1

When i used this xquery iam getting only the name and price.How i can get the type name 'SWEATERS' along with name and price

The XPath 1.0 expression should be:

//category/type/product[itemNumber=1]/*[self::name or self::price]|
//category/type[product[itemNumber=1]]

Or more staticly:

//category/type/product[itemNumber=1]/*[self::name or self::price]|
//category/type[@name='SWEATERS']
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to select the type element, you have to change your expression to:

//category/type[product/itemNumber=1]

Or for just the name:

//category/type[product/itemNumber=1]/@name

1 Comment

It is working fine.But it giving all the values with item number 1 and 2
0

I'm afraid you can't do it with a single query with Xpath but you can do it with DOMNode->parentNode.

Comments

0

you can try something like:

$xml->xpath('//category/type[product/itemNumber=1]/(@name | product[itemNumber=1]/(name | price))');

this selects one attribute and two elements. The | is a union operator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.