php - XML 获取命名空间节点值

标签 php xml simplexml

我有这个 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/

相关文章:

php - shell_exec() 超时管理 & exec()

php - 确保每个用户从一台计算机访问 Web 应用程序

php - 从 Soap Response PHP 获取属性值

php - 使用 SimpleXML 计算 xml 元素/节点

php - Mysql从指向同一个表的多个外键中选择数据

php - 这个查询有什么问题?为什么本地结果不同?

java - 如何使用 Jackson 将 POJO 转换为 XML

java - 从 zipFile 的 byteArray 获取 XML 数据

c# - XElement 有类似 XmlNodeList 的东西吗

php - SimpleXML:获取属性可变的值