SimpleXML: Selecting Elements Which Have A Certain Attribute Value

人盡茶涼 提交于 2019-11-25 22:36:01

问题


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.


回答1:


Try this XPath:

/object/data[@type="me"]

So:

$myDataObjects = $simplexml->xpath('/object/data[@type="me"]');

And if object is not the root of your document, use //object/data[@type="me"] instead.




回答2:


I just made a function to do this for me; it only grabs the first result though. Your mileage may vary.

function query_attribute($xmlNode, $attr_name, $attr_value) {
  foreach($xmlNode as $node) { 
    switch($node[$attr_name]) {
      case $attr_value:
        return $node;
    }
  }
}

Usage:

echo query_attribute($MySimpleXmlNode->Customer, "type", "human")->Name;

(For the XML below)

<Root><Customer type="human"><Name>Sam Jones</name></Customer></Root>


来源:https://stackoverflow.com/questions/992450/simplexml-selecting-elements-which-have-a-certain-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!