我有这个 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 block 。那么如何获取节点的值,而不是被破坏的对象树呢?
人们认为 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"
关于php - XML 获取命名空间节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28281050/