我使用 tdom 版本 0.8.2 来解析 html 页面。
从帮助页面我找到了以下命令来获取 ElementById
set html {<html>
<head>
</head>
<body>
<div id="m">
</div>
</body>
</html>
}
package require tdom
set doc [ dom parse -html $html ]
set node [ $doc getElementById m]
Run Code Online (Sandbox Code Playgroud)
但是当我执行第二个 set 命令时,我得到一个空字符串。但显然该标签的 id 为 m 。有人能告诉我哪里出了问题吗?
问候, 米图恩
问题是您的文档缺少<!DOCTYPE>
声明,因此 tDOM 不知道id
元素将被解释为 ID。
如果我们添加 DOCTYPE,一切都会起作用......
package require tdom
set html {<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">
<html>
<head>
</head>
<body>
<div id="m">
</div>
</body>
</html>}
set doc [ dom parse -html $html ]
set node [ $doc getElementById m]
puts [$node asList]
Run Code Online (Sandbox Code Playgroud)
为我产生这个输出:
div {id m} {}
Run Code Online (Sandbox Code Playgroud)
您可以通过执行搜索来查看是否可以使用 XPath 找到该元素来检查文档是否正在被解析,如下所示:
puts [[$doc selectNodes "//*\[@id\]"] asList]
Run Code Online (Sandbox Code Playgroud)
由于这确实产生了正确的输出(如上所述),很明显,问题必须出在属性的解释上,而属性又直接指向缺失的 DOCTYPE。
这实际上是 tDOM 0.8.3 中修复的一个错误。