xpath查询似乎失败了

时间:2015-06-22 16:07:43

标签: xml xpath

有人可以告诉我这个失败的原因 xpath查询:

//Pages/*[(name() = 'Home')  or following-sibling::Home] 

在这个xml结构上:

<Pages>
    <copyright>me inc. 2015,</copyright>
    <author>Me</author>
    <lastUpdate>2/1/1999</lastUpdate>

    <Home>--------------------</Home>
    <About>--------------------</About>
    <Contact>------------------</Contact> 
</Pages>

只返回版权元素,这是反对的 我的目标(抓住Pages和home之间的所有元素。 即:copyright,author,lastUpdate和整个Home)。 或者我做错了吗?

&#13;
&#13;
public function fetchAsArray( $pathToRecord, $conversionOption = array() ) {
    if( $pathToRecord == null){
         $this->Err['code'] = ERR_EMPTY_XPATH_QUERY;      
         $this->Err['msg'] = " Specified path to an xml file is non-existent "; 
           return false;
    }
        
    $xml = simplexml_import_dom($this->xmlObj);
    $result = $xml->xpath( $pathToRecord );        //unknown node handle 
        
    if ($result === false) { 
       $this->parseError();                   //To return xml Error code
       return false ; 
    }
        
    if (empty($result)) { 
       return NO_RECORD_FOUND;
     }  

   return $this->strToArray($result[0]->saveXML());       //strToArray() is here: https://gist.github.com/laiello/8189351
}
&#13;
&#13;
&#13;

&#13;
&#13;
/*
     inside myXMLManager::fetchAsArray(), i did this:

     foreach( $result as $val ) {echo $xml->saveXML($val);}
     
     returned Error was, Warning: SimpleXMLElement::saveXML( ): failed to open stream: Invalid argument in
     lib\myXMLManager.php on line 205.

     next, changing $result to result[0] in the same foreach returned null.
     lastly, just doing var_dump($result[0]); returned null, while 
     var_dump($result) returned:
     
     array (size=4)
     0 => 
    object(SimpleXMLElement)[8]
     1 => 
    object(SimpleXMLElement)[9]
     2 => 
    object(SimpleXMLElement)[10]
     3 => 
    object(SimpleXMLElement)[11]

    null

       whats' wrong ? or could it be from the call to strToArray() henceforth ?
*/​
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

$str = '<root><Pages>
    <copyright>me inc. 2015,</copyright>
    <author>Me</author>
    <lastUpdate>2/1/1999</lastUpdate>

    <Home>--------------------</Home>
    <About>--------------------</About>
    <Contact>------------------</Contact> 
</Pages></root>';

$xml = simplexml_load_string($str);
$result = $xml->xpath('//Pages/*[(name() = "Home")  or following-sibling::Home]');        
    if ($result === false) { 
       $this->parseError();                   //To return xml Error code
       return false ; 
    }

    if (empty($result)) { 
       return NO_RECORD_FOUND;
     }  

   foreach($result as $r) echo $r->getName()."\n";

结果

copyright
author
lastUpdate
Home