【问题标题】:XML Xpath Failing on getElementsByTagNameXML Xpath 在 getElementsByTagName 上失败
【发布时间】:2014-03-01 18:23:30
【问题描述】:
<?xml version="1.0" encoding="UTF-8"?>
<AddProduct>
<auth><id>vendor123</id><auth_code>abc123</auth_code></auth>
</AddProduct>

我做错了什么:致命错误:调用未定义的方法 DOMNodeList::getElementsByTagName()

$xml = $_GET['xmlRequest'];
$dom = new DOMDocument();
@$dom->loadXML($xml);

$xpath = new DOMXPath($dom);

$auth = $xpath->query('*/auth');
$id = $auth->getElementsByTagName('id')->item(0)->nodeValue;
$code = $auth->getElementsByTagName('auth_code')->item(0)->nodeValue;

【问题讨论】:

  • 如果我可以提出建议,请不要在调试时使用@ 来抑制错误警告。
  • 尝试将您的 XPath 更改为 //auth/AddProduct/auth
  • 实际上,经过进一步审查,DOMXpath 没有getElementsByTagName 属性,但DOMDocument 确实有。
  • @Ohgodwhy 感谢您的推荐!它让我遇到了真正的问题,那就是 XML 充满了从 emacs 复制和粘贴的反斜杠。哇!

标签: php xml xpath


【解决方案1】:

您可以仅使用 XPath 检索您想要的数据(在您发布的 XML 中):

$id = $xpath->query('//auth/id')->item(0)->nodeValue;
$code = $xpath->query('//auth/auth_code')->item(0)->nodeValue;

正如@Ohgodwhy 在 cmets 中指出的那样,您还在 $auth (DOMXPath) 上调用 getElementsByTagName(),这会导致错误。如果你想使用它,你应该打电话给$dom

您的 XPath 表达式返回 current(上下文)节点的 auth 子节点。除非您的 XML 文件不同,否则使用以下之一会更清楚:

/*/auth           # returns auth nodes two levels below root
/AddProduct/auth  # returns auth nodes in below /AddProduct
//auth            # returns all auth nodes

【讨论】:

  • 如果将 query() 替换为 evaluate(),则可以通过在 Xpath 中强制转换结果列表来直接获取值。 $id = $xpath-&gt;evaluate('string(//auth/id)');
  • 谢谢!这很好用。奖励是因为这是我在代码中使用的。
【解决方案2】:

这是我在查看 php 文档后得出的结论(http://us1.php.net/manual/en/class.domdocument.phphttp://us1.php.net/manual/en/domdocument.loadxml.phphttp://us3.php.net/manual/en/domxpath.query.phphttp://us3.php.net/domxpath

$dom = new DOMDocument();
$dom->loadXML($xml);
$id = $dom->getElementsByTagName("id")->item(0)->nodeValue;
$code = $dom->getElementsByTagName("auth_code")->item(0)->nodeValue;

正如helderdarocha 和 Ohgodwhy 所指出的,getElementByTagName 是一种 DOMDocument 方法而不是 DOMXPath 方法。我喜欢 Holderdarocha 的只使用 XPath 的解决方案,我发布的解决方案完成了同样的事情,但只使用了 DOMDocument。

【讨论】:

    猜你喜欢
    • 2015-09-08
    • 2023-04-03
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    相关资源
    最近更新 更多