空白“DOMNodeList”通过Xpath读取XML

时间:2017-11-16 03:04:42

标签: php xml xpath

我试图通过下面给出的XML通过下面的PHP代码读取“SIM”的值,但由于某种原因它给了我一个空白的“DOMNodeList”任何想法我在这里做错了什么?我想将该元素设置为

<ns1:SIM old="8902"> 000000 </SIM>

我该怎么做,因为我正在尝试使用下面的代码来查找它,但似乎输出“DOMNodeList”为空。

$xpath = new DOMXPath($doc);
$xpath->registerNamespace('ns1', 'http://www.example.com/WSG/ec/');
$result = $xpath->query("/ns1:ModifySIMRequest/ns1:ServiceProfile/ns1:Primary/ns1:SIM");
        foreach ($result AS $node) {
            var_dump($node);
            echo $node->nodeValue;
        }

$ doc中的XML是

<?xml version="1.0"?>
<ns1:ModifySIMRequest xmlns:ns1="http://www.example.com/WSG/ec/">
  <ns1:ServiceProfile>
    <ns1:Speech>
      <ns1:MSN>33808089</ns1:MSN>
      <ns1:AccountNumber>8989895</ns1:AccountNumber>
    </ns1:Speech>
    <ns1:Primary action="mod">
      <ns1:BillingOption>dsdsd</ns1:BillingOption>
      <ns1:SIM old="8902"/>
    </ns1:Primary>
  </ns1:ServiceProfile>
</ns1:ModifySIMRequest>

2 个答案:

答案 0 :(得分:1)

获取属性

        echo $node->getAttribute('old');  // 8902

设定值

        $node->nodeValue = '000000';
        echo $doc->saveXML(); // <ns1:SIM old="8902">000000</ns1:SIM>

答案 1 :(得分:1)

元素{http://www.example.com/WSG/ec/}SIM的文本内容/节点值为空。如果你想在这里获取属性有两种方法。您可以使用DOM方法读取属性值或扩展Xpath表达式以获取属性节点。如果你获取属性,你甚至可以直接将它转换为Xpath表达式中的字符串。

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXPath($document);
$xpath->registerNamespace('ec', 'http://www.example.com/WSG/ec/');

$result = $xpath->evaluate("/ec:ModifySIMRequest/ec:ServiceProfile/ec:Primary/ec:SIM");
foreach ($result AS $node) {
  // use the DOM method to fetch the attribute
  var_dump($node->getAttribute('old'));
}

// fetch the attribute node using Xpath
$result = $xpath->evaluate("/ec:ModifySIMRequest/ec:ServiceProfile/ec:Primary/ec:SIM/@old");
foreach ($result AS $node) {
  var_dump($node->textContent);
}

var_dump(
  // fetch the value of the first matching attribute as a string
  $xpath->evaluate("string(/ec:ModifySIMRequest/ec:ServiceProfile/ec:Primary/ec:SIM/@old)")
);

注意:命名空间别名/前缀不需要与文档中的别名匹配。你可以使用更有意义的一个。

相关问题