【发布时间】:2014-06-17 20:44:20
【问题描述】:
我在弄清楚如何从 HTML 文件中选择特定 HTML 元素(实际上是节点)中的内容时遇到了很多麻烦。
我首先承认这不是“格式良好的 xml”,但除非这真的是我的问题,否则我怀疑它真的很重要。拿下这个文件:
<html>
<body id="464">
<div id="fullname"> Use Cases </div>
<div id="intro"> <b><font color="#000033">Use Cases </font></b> </div>
</body>
</html>
这是我从完整脚本中提取的非常简单的代码:
xmlSourceTranslation = new ActiveXObject("Msxml2.DOMDocument.6.0");
xmlSourceTranslation.async="false";
xmlSourceTranslation.load(file.html);
xmlSourceTranslation = xmlSourceTranslation.documentElement;
var sourceNode = xmlSourceTranslation.selectSingleNode("//*[@id = 'fullname']");
if (typeof sourceNode === 'object') {
sourceText = sourceNode.firstChild.nodeValue;
}
问题是,取决于我是否得到fullname 或intro div,以及我使用的方法(.firstChild.nodeValue、.innerHTML、.firstChild.innerHMTL、.childNodes),我要么得到一个null、undefined 的值,否则我会在尝试访问它时出现 Object Required 错误。我可以使用的唯一可靠方法是sourceNode.text,它每次都有效,但只能在intro div 中获取“用例”作为值,而不是我需要的 HTML。
近 2 天以来,我一直在办公桌上敲我的头,试图弄清楚。
【问题讨论】: