基本的DOMXpath,会出错吗? (关于:始终检查输入名称空间) [英] Basic DOMXpath, can be wrong? (re: check input namespace always)

查看:44
本文介绍了基本的DOMXpath,会出错吗? (关于:始终检查输入名称空间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将内部domDocument用作类 $ this-> doc-> dom ,并且我认为这是可以的,因为 $ this-> doc-> dom-> saveXML()起作用,并显示我的XML,例如

I am using a internal domDocument into a class, $this->doc->dom, and I think that is ok because $this->doc->dom->saveXML() works, and show my XML, something like

  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
      <title>04</title>
      <link href="css/04.css" rel="stylesheet" type="text/css"/>
    </head>
   ...

当我使用

 $xpath = new DOMXpath($this->doc->dom);
 $elements = $xpath->query('//link'); 

没有错误报告...但是,没有元素(!),

no error reported... But, no elements (!),

   print $elements->length;

显示0(零)。 那是问题,对我来说,这是一个DomDocument错误:< link ../& gt; 元素在那里!

show 0 (zero). That is the problem, and for me is a DomDocument BUG: the <link ../> element is there!

编辑以添加更多线索...

Edit to add more clues...

当我做类似的事情时与 getElementsByTagName()一起使用(!),所以 $ this-> doc-> dom

When I do similar thing with getElementsByTagName() it works (!), so, is not a problem with the $this->doc->dom.

 $test = $this->doc->dom->getElementsByTagName('link');
 print $test->length; // OK, not zero, returns 1!


推荐答案

它不是 DomDocument错误。

It is not a "DomDocument bug".

合并发布的评论。

(@ PaulT回答) 
根( html 标记)具有声明的名称空间, xmlns = http://www.w3.org/1999/xhtml
使用 registerNamespace(),可以使用任意昵称(xx)进行注册,然后进行正确的查询

(@PaulT answer)   The root (html tag) have a namespace declared, xmlns="http://www.w3.org/1999/xhtml". With registerNamespace() you can register it, with an arbitrary nickname (xx), then do a correct query

$xpath->registerNamespace('xx', "http://www.w3.org/1999/xhtml"); 
$xpath->query('//xx:link');



从根目录删除命名空间属性



I过滤我的输入,因此将其更改为

Remove namespace attribute from root

I an filtering my input, so it changed to

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<html>
 <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>04</title>
    <link href="css/04.css" rel="stylesheet" type="text/css"/>
 </head>
...
</html>

现在正在按预期工作,不需要该死的命名空间。

now is working as I expected, without need of "damn namespaces".

(@ RolandoIsidoro答案) 
在此类情况下遇到麻烦时,请尝试使用 freeformatter.com/xpath-tester这样的工具。 html
在您的示例中,它引发了一个错误,可能会导致您找到解决方案:

(@RolandoIsidoro answer)   When in trouble in cases like these try a tool like freeformatter.com/xpath-tester.html. In your example it throws an error that would have lead you to the solution:


默认(无前缀)命名空间URI对于XPath查询始终为''
,并且无法将其重新定义为' http://www.w3 .org / 1999 / xhtml '

这篇关于基本的DOMXpath,会出错吗? (关于:始终检查输入名称空间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆