doufenzhu7012 2013-05-06 21:54
浏览 72
已采纳

如何使用命名空间获取属性的值

I'd like to get the content of the attribute xsi:schemaLocation. It's works perfectly with getElementsByTagName in php (and foreach after) but it's ugly, right ?

How to get the same content with a simple Xpath query ?

Here a short example of the xml content :

<?xml version="1.0" encoding="utf-8"?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" version="1.0" creator="blabla" xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0/1 http://www.groundspeak.com/cache/1/0/1/cache.xsd" xmlns="http://www.topografix.com/GPX/1/0">
...
</gpx>

Thanks!

  • 写回答

2条回答 默认 最新

  • douweng7308 2013-05-06 22:15
    关注

    Using the SimpleXMLElement class you can easily get the attribute xsi:schemaLocation's value:

    <?php
    $xml = <<<XML
    <?xml version="1.0" encoding="utf-8"?>
    <gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" version="1.0" creator="blabla" xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0/1 http://www.groundspeak.com/cache/1/0/1/cache.xsd" xmlns="http://www.topografix.com/GPX/1/0">
    </gpx>
    XML;
    
    $sxe = new SimpleXMLElement($xml);
    $schemaLocation = $sxe->attributes('xsi', true)->schemaLocation;
    
    echo (string) $schemaLocation;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?