简体   繁体   中英

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>
   </type>
   <type name="PANTS">
        <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]');

The out put will give the itemNumber name and price.How i can get the type name i mean SWEATERS

You can get this using the parent .. , then the @name attribute.

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

xPath Syntax

您正在寻找具有id为1的product元素的类型的name属性:

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

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