Php 使用xpath和xquery解析xml文件

Php 使用xpath和xquery解析xml文件,php,xml,xpath,xquery,Php,Xml,Xpath,Xquery,我有一个xml文件 <category> <type name="SWEATERS"> <product id =1> <itemNumber>1</itemNumber> <name>ProductA2</name> <price>345</price> </produc

我有一个xml文件

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

使用此xquery时,我仅获取名称和价格。如何获取类型名称“毛衣”以及名称和价格如果要选择类型元素,必须将表达式更改为:

//类别/类型[产品/项目编号=1]

或者只是为了名字:


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

恐怕您无法使用Xpath进行单个查询,但可以使用
DOMNode->parentNode
进行查询。您可以尝试以下操作:

$xml->xpath('//category/type[product/itemNumber=1]/(@name | product[itemNumber=1]/(name | price))');
这将选择一个属性和两个元素。
|
是一个并集运算符

当我使用这个xquery时 只有名字和价格。我怎么能买到 类型名称“毛衣”以及 名称和价格

XPath 1.0表达式应为:

//category/type/product[itemNumber=1]/*[self::name or self::price]|
//category/type[product[itemNumber=1]]
或者更静态地说:

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

它工作正常。但是它给出了所有项目编号为1和2的值
//category/type/product[itemNumber=1]/*[self::name or self::price]|
//category/type[@name='SWEATERS']