我可以使用 SimpleXML &Xpath 直接选择元素属性? [英] Can I use SimpleXML & Xpath to directly select an Elements Attribute?

查看:26
本文介绍了我可以使用 SimpleXML &Xpath 直接选择元素属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即- 我想使用类似 xpath 表达式//banana/@color"和以下示例 xml 的内容返回一个字符串yellow"...

i.e. - i want to return a string "yellow" using something like xpath expression "//banana/@color" and the following example xml...

<fruits>
 <kiwi color="green" texture="hairy"/>
 <banana color="yellow" texture="waxy"/>
</fruits>


$fruits = simplexml_load_string(
'<fruits>
 <kiwi color="green" texture="hairy"/>
 <banana color="yellow" texture="waxy"/>
</fruits>');

print_r($fruits->xpath('//banana/@color'));

生产

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [color] => yellow
                )

        )

)

而我更喜欢......

whereas i would prefer something like...

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => yellow
        )

)

...这样我就不需要在我正在编写的应用程序中写入特殊情况.

...so that i don't need to write a special case into the application i'm writing.

非常感谢!:)

推荐答案

我只是试了一下你的测试,因为我很好奇,我发现当转换为字符串.

I just gave your test a shot because i was curious and I found that it does actually produce the string value yellow when converted to string.

$fruits = simplexml_load_string(
'<fruits>
 <kiwi color="green" texture="hairy"/>
 <banana color="yellow" texture="waxy"/>
</fruits>');

$found = $fruits->xpath('//banana/@color');
echo $found[0];

这似乎就是 SimpleXmlElement 属性节点的表示方式.因此,如果您不直接打印/回显它,则可以将其用作 (string) $found[0] .

It would seem this is just how SimpleXmlElement attribute nodes are represented. So you can use this as (string) $found[0] if you are not printing/echoing it directly.

当然,如果您依赖于剩余的 SimpleXMLElement 值,那么我想这可能是一个问题.但我认为只要记住在稍后使用节点时将其转换为字符串仍然可行.

Of course if your depending on the value remaining a SimpleXMLElement then that could be an issue I suppose. But i would think just remembering to cast as string when you go to use the node later would still be doable.

如果你真的需要一个支持属性作为节点的节点的详细接口,那么你可能只想切换到 DOMDocument.你的代码会变得更冗长,但实现更清晰.

IF you really need a detailed interface for Nodes that supports an Attribute as a node then you may want to just switch to DOMDocument. You code will get more verbose, but the implementation is more clear.

这篇关于我可以使用 SimpleXML &amp;Xpath 直接选择元素属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆