简体   繁体   中英

Parsing xml file using xpath and xquery

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

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

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

恐怕您无法使用Xpath进行单个查询,但是可以使用DOMNode->parentNode

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

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