【问题标题】:php xpath retrieving attribute-values based on multiple attributes and parent-attributesphp xpath基于多个属性和父属性检索属性值
【发布时间】:2013-03-01 12:55:06
【问题描述】:

我需要从xml中选择节点,条件见下文。我使用的是 simplexml,所以 xpath 必须是 1.0。

XML sn-p:

<scales>
    <scale id="1" gender="*" age="*">
        <d scid="hi" raw="10" t="76" />
        <d scid="pn" raw="12" t="80" />
    </scale>
    <scale id="2" gender="m" age="*">
        <d scid="hi" raw="8" t="79" />
        <d scid="pn" raw="2" t="50" />
    </scale>
    <scale id="3" gender="*" age="19-39">
        <d scid="hi" raw="0" t="48" />
        <d scid="pn" raw="10" t="49" />
    </scale>
</scales>

现在,我想选择具有...的&lt;d&gt; 节点的t-Attribute...

 raw="10" AND scid="hi"

 $result=$xml->xpath('//d[@scid="hi"][@raw="10"]/@t');

它的父节点&lt;scale&gt; 有...

(gender="*" OR gender="m") AND (age="*" OR age="39-59")

$result=$xml->xpath('//scale[@gender="*" or @gender="m"][@age="*" or @age="39-59"]');

我想通过我的 simplexml-object $xml 中的 1 个 xpath-statement 来获取它。

【问题讨论】:

  • 您的 XML 中有一个错误,至少 raw="12 is missing a " 这可能没有用,或者只是这里的输入错误?
  • @Dave:谢谢,打错字了,编辑了
  • 您能否提供一些实际的 php 代码,例如您目前尝试查询它的方式

标签: php xpath simplexml


【解决方案1】:

只需结合您的两个 XPath 查询...

Live demo

$str=<<<XML
<scales>
    <scale id="1" gender="*" age="*">
        <d scid="hi" raw="10" t="76" />
        <d scid="pn" raw="12" t="80" />
    </scale>
    <scale id="2" gender="m" age="*">
        <d scid="hi" raw="8" t="79" />
        <d scid="pn" raw="2" t="50" />
    </scale>
    <scale id="3" gender="*" age="19-39">
        <d scid="hi" raw="0" t="48" />
        <d scid="pn" raw="10" t="49" />
    </scale>
</scales>
XML;
$xml=simplexml_load_string($str);
foreach($xml->xpath('//scale[@gender="*" or @gender="m"][@age="*" or @age="39-59"]/d[@scid="hi"][@raw="10"]/@t') as $t)
{
    echo $t;
}

输出76

【讨论】:

    【解决方案2】:

    好的,快速读入 xpath 似乎你可以做类似这样的属性匹配

     $path = "(scale[@gender=\"*\"]|scale[@gender=\"m\"]) & (scale[@age=\"*\"]|scale[@age=\"39-59\"])";
     $scale= $xml->xpath($path);
    

    这应该会返回您想要的实际比例标签。 然后你可以 foreach 循环遍历返回的 $scale 中的标签,并使用类似这样的方法提取标准属性(注意不准确但正确的概念)

    foreach($scale->d[0]->attributes() as $a => $b => $c) {
        echo "t=$c\"\n";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多