如何用XPath查询下一个节点


XPath how to query the next node

下面是xml文件的一个示例。如果我的id值是20也就是xml文件的一半。我如何首先搜索该节点,然后找到下一个(以下)值。

<League>
  <Id>20</Id>
  <Name>Major League Soccer</Name>
  <Country>USA</Country>
  <Historical_Data>Partial</Historical_Data>
  <Fixtures>Yes</Fixtures>
  <Livescore>Yes</Livescore>
  <NumberOfMatches>135</NumberOfMatches>
  <LatestMatch>2013-06-16T04:00:00+02:00</LatestMatch>
</League>
<League>
  <Id>33</Id>
  <Name>Allsvenskan</Name>
  <Country>Sweden</Country>
  <Historical_Data>Partial</Historical_Data>
  <Fixtures>Yes</Fixtures>
  <Livescore>Yes</Livescore>
  <NumberOfMatches>88</NumberOfMatches>
  <LatestMatch>2013-06-15T16:00:00+02:00</LatestMatch>
</League>

因为《League with id = 20》是XML文件的一半,所以可以使用XPath动态地完成它。下面是一个简单的PHP代码片段:

<?php
$xml = <<<XML
<Leagues>
    <League>
        <Id>20</Id>
        <Name>Major League Soccer</Name>
        <Country>USA</Country>
        <Historical_Data>Partial</Historical_Data>
        <Fixtures>Yes</Fixtures>
        <Livescore>Yes</Livescore>
        <NumberOfMatches>135</NumberOfMatches>
        <LatestMatch>2013-06-16T04:00:00+02:00</LatestMatch>
    </League>
    <League>
        <Id>33</Id>
        <Name>Allsvenskan</Name>
        <Country>Sweden</Country>
        <Historical_Data>Partial</Historical_Data>
        <Fixtures>Yes</Fixtures>
        <Livescore>Yes</Livescore>
        <NumberOfMatches>88</NumberOfMatches>
        <LatestMatch>2013-06-15T16:00:00+02:00</LatestMatch>
    </League>
</Leagues>
XML;
$sxe = new SimpleXMLElement($xml);
// Retrieve league with Id = 20
$league20 = $sxe->xpath("//League[Id='20']");
print_r($league20);
// Retrieve league right after the one with Id = 20
$leagueAfter20 = $sxe->xpath("//League[Id='20']/following-sibling::League[1]");
print_r($leagueAfter20);

输出
Array
(
[0] => SimpleXMLElement Object
    (
        [Id] => 20
        [Name] => Major League Soccer
        [Country] => USA
        [Historical_Data] => Partial
        [Fixtures] => Yes
        [Livescore] => Yes
        [NumberOfMatches] => 135
        [LatestMatch] => 2013-06-16T04:00:00+02:00
    )
)
Array
(
[0] => SimpleXMLElement Object
    (
        [Id] => 33
        [Name] => Allsvenskan
        [Country] => Sweden
        [Historical_Data] => Partial
        [Fixtures] => Yes
        [Livescore] => Yes
        [NumberOfMatches] => 88
        [LatestMatch] => 2013-06-15T16:00:00+02:00
    )
)