gpt4 book ai didi

php - Simplexml xpath 和 xmlns

转载 作者:行者123 更新时间:2023-12-02 11:05:57 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com