2

我知道这是重复的,但我无法在这个上应用答案:LINK 我可以在没有 xmlns 的情况下解析 XML,但我正在解析的提要正在使用它,所以......

工作 XML:

<DPS>
<Buses>
<DpsBus>
<SiteId>9520</SiteId>
<StopAreaNumber>75821</StopAreaNumber>
<TransportMode>BUS</TransportMode>
<StopAreaName>Södertälje centrum</StopAreaName>
<LineNumber>754</LineNumber>
<Destination>Geneta (Scaniarinken)</Destination>
<TimeTabledDateTime>2013-10-31T16:08:00</TimeTabledDateTime>
<ExpectedDateTime>2013-10-31T16:08:00</ExpectedDateTime>
<DisplayTime>0 min</DisplayTime>
</DpsBus>
</Buses>
</DPS>

非工作 XML

<DPS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www1.sl.se/realtidws/">
<Buses>
<DpsBus>
<SiteId>9520</SiteId>
<StopAreaNumber>75821</StopAreaNumber>
<TransportMode>BUS</TransportMode>
<StopAreaName>Södertälje centrum</StopAreaName>
<LineNumber>754</LineNumber>
<Destination>Geneta (Scaniarinken)</Destination>
<TimeTabledDateTime>2013-10-31T16:08:00</TimeTabledDateTime>
<ExpectedDateTime>2013-10-31T16:08:00</ExpectedDateTime>
<DisplayTime>0 min</DisplayTime>
</DpsBus>
</Buses>
</DPS>

PHP

$xmldata = '<DPS xmlns:xsi="..."';
$xml = simplexml_load_string($xmlData);
$arrLines = $xml->xpath('/DPS/Buses/DpsBus[TransportMode="BUS"]');
foreach($arrLines as $line) {
    echo $line->LineNumber.'<br>';
}

这里有什么想法吗?谢谢!

4

1 回答 1

1

通过注册命名空间registerXPathNamespace()并更新 XPath:/r:DPS/r:Buses/r:DpsBus[r:TransportMode="BUS"]

然后你更新的 PHP 代码:

<?php
$xmlData = <<<XML
<?xml version="1.0"?>
<DPS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www1.sl.se/realtidws/">
  <Buses>
    <DpsBus>
      <SiteId>9520</SiteId>
      <StopAreaNumber>75821</StopAreaNumber>
      <TransportMode>BUS</TransportMode>
      <StopAreaName>Södertälje centrum</StopAreaName>
      <LineNumber>754</LineNumber>
      <Destination>Geneta (Scaniarinken)</Destination>
      <TimeTabledDateTime>2013-10-31T16:08:00</TimeTabledDateTime>
      <ExpectedDateTime>2013-10-31T16:08:00</ExpectedDateTime>
      <DisplayTime>0 min</DisplayTime>
    </DpsBus>
  </Buses>
</DPS>
XML;

$xml = simplexml_load_string($xmlData);
$xml->registerXPathNamespace('r', 'http://www1.sl.se/realtidws/');
$arrLines = $xml->xpath('/r:DPS/r:Buses/r:DpsBus[r:TransportMode="BUS"]');
foreach ($arrLines as $line) {
    echo $line->LineNumber, "<br>\n";
}

产生您想要的输出:

754<br>
于 2013-10-31T18:18:54.847 回答