php - Simplexml xpath 和 xmlns

标签 php xpath simplexml

我知道这是重复的,但我无法将答案应用于此: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>';
}

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

最佳答案

通过 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>

关于php - Simplexml xpath 和 xmlns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19711382/

相关文章:

css - selenium - 带有 css 定位器的 href 的存储命令是什么

php - 使用破折号引起的未定义常量?

php - 使用 SimpleXML 不再存在节点

php - 连接 POS 到电子商务 RESTFUL API

Python:If 语句和 Scrapy XPath 选择器

无论执行如何,PHP 更新显示的成功消息

python - 为什么每次在 Selenium Webdriver 中,任何 Web 元素的 “ID” 都会发生变化?

php - 简单 XML- "Node no longer exists"

php - 获取推特屏幕名称

java - 万磁王 : Adding configurable product to cart fails : Please specify the product's option(s)