我正在使用PHP和xpath从API调用解析XML结果。

 $dom = new DOMDocument();
 $dom->loadXML($response->getBody());

 $xpath = new DOMXPath($dom);
 $xpath->registerNamespace("a", "http://www.example.com");

 $hrefs = $xpath->query('//a:Books/text()', $dom);

 for ($i = 0; $i < $hrefs->length; $i++) {
      $arrBookTitle[$i] = $hrefs->item($i)->data;
 }

 $hrefs = $xpath->query('//a:Books', $dom);

 for ($i = 0; $i < $hrefs->length; $i++) {
      $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
 }

这有效但有没有办法可以从一个查询中访问文本和属性?如果是这样,一旦执行查询,您如何获得这些项目?

有帮助吗?

解决方案

在做了一些环顾之后,我遇到了这个解决方案。这样我就可以获取元素文本并访问节点的任何属性。

$hrefs = $xpath->query('//a:Books', $dom);

for ($i = 0; $i < $hrefs->length; $i++) {
    $arrBookTitle[$i] = $hrefs->item($i)->nodeValue;
    $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
}

其他提示

一个单独的XPath表达式,它将选择“a:Books”的文本节点。和他们的“DeweyDecimal”属性,是以下

// a:Books / text()| //一个:图书/ @ DeweyDecimal

请注意在上面的表达式中使用XPath的union运算符。

另一个注释:尽量避免使用“//”缩写,因为它可能导致遍历整个XML文档,因此非常昂贵。当XML文档的结构已知时,建议使用更具体的XPath表达式(例如由一系列特定位置步骤组成)。

如果您只是从XML文档中检索值,请 SimpleXML 可能是更精简,速度更快,内存更友好的解决方案:

$xml=simplexml_load_string($response->getBody());
$xml->registerXPathNamespace('a', 'http://www.example.com');
$books=$xml->xpath('//a:Books');
foreach ($books as $i => $book) {
    $arrBookTitle[$i]=(string)$book;
    $arrBookDewey[$i]=$book['DeweyDecimal'];
}

你能查询串联吗?

$xpath->query('concat(//a:Books/text(), //a:Books/@DeweyDecimal)', $dom);

XSLT本身就是一种表达式语言,您可以在表达式中构造所需的任何特定返回值格式。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top