>我有这个xml片段:
<ModelList>
<ProductModel>
<CategoryCode>06</CategoryCode>
<Definition>
<ListProperties xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:KeyValueOfstringArrayOfstringty7Ep6D1>
<a:Key>Couleur principale</a:Key>
<a:Value>
<a:string>Blanc</a:string>
<a:string>Noir</a:string>
<a:string>Gris</a:string>
<a:string>Inox</a:string>
<a:string>Rose</a:string>
我正在尝试用这个解析(使用 simplexml):
$xml->registerXPathNamespace('a', 'http://schemas.microsoft.com/2003/10/Serialization/Arrays');
$x = $xml->xpath('//a:KeyValueOfstringArrayOfstringty7Ep6D1');
//var_dump($x);
foreach($x as $k => $model) {
$key = (string)$model->Key;
var_dump($model->Key);
}
该 var 转储当前返回一大堆
object(SimpleXMLElement)[7823]
它似乎包含 a:Value 块。那么如何获取节点的值,而不是爆炸的对象树呢?
人们认为xml很容易解析。
听起来你的问题更多的是SimpleXML和XML本身。您可能想尝试 DOM。
可以在 XPath 本身中强制转换结果,因此表达式将直接返回标量值。
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('a', 'http://schemas.microsoft.com/2003/10/Serialization/Arrays');
$items = $xpath->evaluate('//a:KeyValueOfstringArrayOfstringty7Ep6D1');
foreach ($items as $item) {
$key = $xpath->evaluate('string(a:Key)', $item);
var_dump($key);
}
输出:
string(18) "Couleur principale"
所以我最终解决了这个问题。作为参考(经过大量试验和错误,包括基于 ThW 答案的解决方案),此代码正确获取 key 属性:
$xml->registerXPathNamespace('a', 'http://schemas.microsoft.com/2003/10/Serialization/Arrays');
$x = $xml->xpath('//a:KeyValueOfstringArrayOfstringty7Ep6D1/a:Key');
//var_dump($x);
foreach($x as $k => $model) {
var_dump((string)$model);
}