我可以使用 SimpleXML & Xpath直接选择元素属性?
即 - 我想使用类似于 xpath 表达式“//banana/@color”和以下示例 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
)
)
)
返回字符串“yellow”,而我更喜欢类似...
Array
(
[0] => SimpleXMLElement Object
(
[0] => 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'));
produces
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.
thanks very much! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我只是尝试了一下你的测试,因为我很好奇,我发现它在转换为字符串时实际上确实产生了字符串值
yellow
。看起来这就是
SimpleXmlElement
属性节点的表示方式。因此,如果您不直接打印/回显它,则可以将其用作(string) $found[0]
。当然,如果您依赖于
SimpleXMLElement
的剩余值,那么我认为这可能是一个问题。但我认为稍后使用节点时记住将其转换为字符串仍然是可行的。如果您确实需要一个支持属性作为节点的详细节点接口,那么您可能只想切换到 DOMDocument 。您的代码将变得更加冗长,但实现更加清晰。
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.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.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.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.