1
<?xml version="1.0" encoding="UTF-8"?>
<root>
     <channel>
          <item>
                <category>Cat1</category>
          </item>
          <item>
                <category>Cat1</category>
          </item>
          <item>
                <category>Cat2</category>
          </item>
          <item>
                <category>Cat3</category>
          </item>
     </channel>    
</root>

我有这个 xml,我如何得到一个项目的最后一个类别而不重复?我尝试:

<?php
        $DOMDocument = new DOMDocument( '1.0', 'utf-8' );
        $DOMDocument->preserveWhiteSpace = false;
        $DOMDocument->load( 'xml.xml' );
        $DOMXPath = new DOMXPath( $DOMDocument );
        foreach( $DOMXPath->query('.//channel/item/category[last()]/parent::node()') as $Nodes ){
                 foreach( $Nodes->childNodes as $Node ){
                          $RSS[ $Node->nodeName ] = $Node->nodeValue;
                 }
                 $RSSContents[] = $RSS;
        }
        echo '<pre>';
        print_r( $RSSContents );

但重述:

Array
(
    [0] => Array
        (
            [category] => Cat1
        )

    [1] => Array
        (
            [category] => Cat1
        )

    [2] => Array
        (
            [category] => Cat2
        )

    [3] => Array
        (
            [category] => Cat3
        )

)

我需要退回最后的猫 1 + 其他物品

4

1 回答 1

2

下面的 XPath 应该选择文档中每个类别的最后一项

/root/channel/item[not(category = following::category)]
于 2011-05-16T15:24:11.447 回答