0

我正在尝试使用 php SimpleXML 和 xpath 解析 XML 文件,并且在获取正确的路径和访问属性值时遇到问题。任何帮助表示赞赏。

这是我的 xml 文件:-

<message:MessageGroup xmlns="http://mynamespace.com">
<Book>
<BookKey>
<Value concept="TITLE" value="Gone Girl"/>
<Value concept="AUTHOR" value="Gillian Flynn"/>
</BookKey>
<Sales>
<Month>Jan</Month>
<Number value="20"/>
</Sales>
<Sales>
<Month>Feb</Month>
<Number value="15"/>
</Sales>
<Sales>
<Month>Mar</Month>
<Number value="30"/>
</Sales>
</Book>
<Book>
<BookKey>
<Value concept="TITLE" value="Inferno"/>
<Value concept="AUTHOR" value="Dan Brown"/>
</BookKey>
<Sales>
<Month>Jan</Month>
<Number value="10"/>
</Sales>
<Sales>
<Month>Feb</Month>
<Number value="15"/>
</Sales>
<Sales>
<Month>Mar</Month>
<Number value="3"/>
</Sales>
</Book>
</message:MessageGroup>

我需要解析它以获得以下输出: -

Gone Girl,Gillian Flynn,Jan,20
Gone Girl,Gillian Flynn,Feb,15
Gone Girl,Gillian Flynn,Mar30
Inferno,Dan Brown,Jan,10
Inferno,Dan Brown,Feb,15
Inferno,Dan Brown,Mar,3

我写了以下代码:-

<?php
$xmlfile = 'Books.xml';
$xml = simplexml_load_file($xmlfile);
$namespace = 'http://mynamespace.com';
$xml->registerXPathNamespace('ns',$namespace);
$books = $xml->xpath('//ns:Book');

//loop through each book -

foreach($books as $book) {

$values = $xml->xpath('ns:BookKey/Value');
$bookkeys= array();

//loop through each Book's BookKey Values and push them to array -

foreach($values as $value){  
array_push($bookkeys, $value->attributes()->value);
}    
$sales = $xml->xpath('ns:Sales');

//loop through each Book's Sales and write out Month and Number value after the book key values -

foreach($sales as $sale){  
foreach($bookkeys as $bk){
echo $bk.",";
}
echo $sale->Month;
echo ",";
echo $sale->Number->attributes()->value;
echo "\n";
}
}
?>

从 var_dump 来看,$books 数组似乎没问题;$values 和 $sales 是空数组,所以显然路径不正确。我试过省略命名空间,但仍然得到一个空数组;我想避免提取文件中的所有价值和销售额实例,而不仅仅是每本特定书籍的实例。

4

1 回答 1

1

您缺少前缀的命名空间定义message

要获取valuefrom Valuemessage:MessageGroup/ns:BookKey/ns:Value/@value将是要使用的 XPath。

于 2013-04-26T16:40:53.780 回答