开发者

Implementing condition in XPath [duplicate]

This question already has answers here: SimpleXML: Selecting Elements Which Have A Certain Attribute Value (2 answers) Closed 9 years ago.

I have a XML file

<?xml version="1.0" encoding="UTF-8"?>
<xml>
  <events date="12/12/2010">
    <event>
      <title>JqueryEvent</title>
      <description>
        easily
      </description>
    </event>
  </events>
  <events date="14/12/2011">
    <event>
      <title>automatically onBlur</title>开发者_高级运维;
      <description>
        when a date is selected. For an inline calendar, simply attach the datepicker to a div or span.
      </description>
    </event>
  </events>
</xml>

And I am using this Xpath to select the nodes

$xml   = simplexml_load_file($file);
$nodes = $xml->xpath('//xml/events');

It will select all the nodes.I want to select the nodes based on the date.


Specify the date in the xpath expression,

i.e.

$nodes = $xml->xpath('//xml/events[@date="14/12/2011"]');

would select only the last events-node in the example


Use

$xml = simplexml_load_string($xml);
$nodes = $xml->xpath('//events[@date="14/12/2011"]');
print_r( $nodes );

to get the event node below the xml node with the specified date and

$xml = simplexml_load_string($xml);
$nodes = $xml->xpath('//xml/events[@date]');
print_r( $nodes );

to get all event below the xml node nodes having a date attribute. Likewise, use

$xml = simplexml_load_string($xml);
$nodes = $xml->xpath('//events[contains(@date, "2011")]');
print_r( $nodes );

to find all event nodes anywhere in the document with a date attribute containing the string "2011".

On a sidenote, you can use simplexml_load_file to load an XML file directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜