使用特殊命名空间解析XML

时间:2015-11-17 08:15:20

标签: php xml dom

我有一个看起来像这样的XML文件:

    <?XML version="1.0" encoding="UTF-8"?>
    <test:start xmlns:test="http://www.test.de" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <test:uebertragung art="OFFLINE" version="1.0.0"></test:uebertragung>
    <test:object>
            <test:objectnr>5</test:objectnr>
            <test:objectview>
                    <test:geo>
                            <test:lat>12</test:lat>
                            <test:long>30</test:long>
                    </test:geo>
                    <test:objectcategorie>5</test:objectcategorie>
                    <test:geo>
                            <test:lat>11</test:lat>
                            <test:long>30</test:long>
                    </test:geo>
                    <test:objectcategorie>8</test:objectcategorie>
                    <test:geo>
                            <test:lat>16</test:lat>
                            <test:long>30</test:long>
                    </test:geo>
                    <test:objectcategorie>2</test:objectcategorie>
                    <test:geo>
                            <test:lat>14</test:lat>
                            <test:long>35</test:long>
                    </test:geo>
                    <test:objectcategorie>14</test:objectcategorie>
            </test:objectview>
    </test:object>
    </test:start> 

现在我想在php中解析这个文件。我得到以下代码,只显示第一个对象:

$xmlDoc->load("test.xml");
$x = $xmlDoc->documentElement;
$x = $x->childNodes[1];
$x = $x->childNodes[1];
foreach ($x->childNodes AS $item) {
    print $item->nodeName . " = " . $item->nodeValue . "<br>";
}

有人可以解释一下解析这个XML文件的更简单方法。我想只显示所有“objectsviews”和“objectcategorie”中的“test:lat”。

1 个答案:

答案 0 :(得分:0)

希望这对您解决问题很有用。

    libxml_use_internal_errors( TRUE );

    $dom = new DOMDocument('1.0','utf-8');
    $dom->validateOnParse=false;
    $dom->standalone=true;
    $dom->strictErrorChecking=false;
    $dom->recover=true;
    $dom->load( 'test.xml' );

    libxml_clear_errors();


    $xpath=new DOMXPath( $dom );
    $rns = $dom->lookupNamespaceUri( $dom->namespaceURI ); 
    $xpath->registerNamespace( 'test', $rns );

    $col = $xpath->query('//test:geo');
    foreach( $col as $node ) {
        foreach( $node->childNodes as $cn ){
            if( is_object( $cn ) && $cn->nodeType==1 ) echo $cn->tagName.'='.$cn->nodeValue.'<br />';   
        }
    }

    $dom=$xpath=$rns=$col=null;

/*
    This outputs:
    -------------
    test:lat=12
    test:long=30
    test:lat=11
    test:long=30
    test:lat=16
    test:long=30
    test:lat=14
    test:long=35
*/