1

I need to select nodes from xml, conditions see below. I am using simplexml, so the xpath has to be 1.0.

XML snippet:

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

Now, I want to select the t-Attribute of a <d> node that has...

 raw="10" AND scid="hi"

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

And its parent-node <scale> has...

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

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

I'd like to get this with 1 xpath-statement from my simplexml-object $xml.

2
  • There's an error in your XML at least raw="12 is missing a " which may not be hleping or is that just a mistype on here ? Commented Mar 1, 2013 at 13:08
  • can you provide some actual php code like how you're attempting to query it at the moment Commented Mar 1, 2013 at 13:23

2 Answers 2

4

Just combine your two XPath query...

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

Outputs 76.

Sign up to request clarification or add additional context in comments.

Comments

0

ok quick read into xpath seems like you can do attribute matches something like this

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

This should return you the actual scale tag you want. Then you can foreach loop through the tags within the returned $scale and pull the standard attributes using something like this (note not accurate but right concept)

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

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.