SimpleXML:选择具有特定属性值的元素
在 XML 文档中,我有共享相同名称的元素,但属性的值定义了它的数据类型,并且我想从文档中选择所有具有特定值的元素。 我是否需要使用 XPath(如果需要,您能否建议正确的语法)或者是否有更优雅的解决方案?
下面是一些示例 XML:
<object>
<data type="me">myname</data>
<data type="you">yourname</data>
<data type="me">myothername</data>
</object>
我想选择类型为 me
的
PS - 我正在尝试使用 PHP 与 Netflix API 进行交互 - 这对我的问题来说应该不重要,但如果你想建议一个好的/更好的方法来做到这一点,我洗耳恭听。
In an XML document, I have elements which share the same name, but the value of an attribute defines what type of data it is, and I want to select all of those elements which have a certain value from the document. Do I need to use XPath (and if so, could you suggest the right syntax) or is there a more elegant solution?
Here's some example XML:
<object>
<data type="me">myname</data>
<data type="you">yourname</data>
<data type="me">myothername</data>
</object>
And I want to select the contents of all <data>
tags children of <object>
who's type is me
.
PS - I'm trying to interface with the Netflix API using PHP - this shouldn't matter for my question, but if you want to suggest a good/better way to do so, I'm all ears.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个 XPath:
读作:
/
) 当前元素的子元素 (object
)/
) 他们的子元素 () data
[...]
) 列出元素,其中...类型
(@
表示“属性”)me
所以:
如果
object
不是文档的根目录,您可能需要使用//object/data[@type="me"]
代替。//
表示“查找所有后代”而不是“查找所有子代”。Try this XPath:
Which reads as:
/
) children of the current element calledobject
/
) their children calleddata
[...]
) that list to elements where ...type
(the@
means "attribute")me
So:
If
object
is not the root of your document, you might want to use//object/data[@type="me"]
instead. The//
means "find all descendents" rather than "find all children".我只是做了一个函数来为我做这件事; 但它只获取第一个结果。 你的旅费可能会改变。
用法:(
对于下面的 XML)
I just made a function to do this for me; it only grabs the first result though. Your mileage may vary.
Usage:
(For the XML below)