【问题标题】:Getting proper HTML contents of a DIV (JavaScript WSH, XMLDOM ActiveX)获取 DIV 的正确 HTML 内容(JavaScript WSH、XMLDOM ActiveX)
【发布时间】: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;
}

问题是,取决于我是否得到fullnameintro div,以及我使用的方法(.firstChild.nodeValue.innerHTML.firstChild.innerHMTL.childNodes),我要么得到一个nullundefined 的值,否则我会在尝试访问它时出现 Object Required 错误。我可以使用的唯一可靠方法是sourceNode.text,它每次都有效,但只能在intro div 中获取“用例”作为值,而不是我需要的 HTML。

近 2 天以来,我一直在办公桌上敲我的头,试图弄清楚。

【问题讨论】:

    标签: xml jscript wsh xmldom


    【解决方案1】:
    1. .async 需要一个布尔值(不是字符串)
    2. .load 需要一个字符串
    3. 用其 documentElement 破坏 XML 对象是个坏主意
    4. 在没有错误检查的情况下使用 .load 是一种不好的做法
    5. .selectSingleNode 失败时返回 null

    Minimal 用于 XML 工作的框架(针对您的问题进行了调整):

    var sFSpec = "..\\data\\24272956.xml";
    var sXPath = "//*[@id = 'fullname']";
    var oXml   = new ActiveXObject("Msxml2.DOMDocument.6.0");
    var sOtp   = "???";
    oXml.async = false;
    if (oXml.load(sFSpec)) {
       var ndDE  = oXml.documentElement;
       var ndSrc = ndDE.selectSingleNode(sXPath);
       if (ndSrc !== null) {
          sOtp = ndSrc.firstChild.nodeValue;
       } else {
          sOtp = "no node found for " + sXPath;
       }
    } else {
       sOtp = sFSpec + ": " + oXml.parseError.reason;
    }
    WScript.Echo(sOtp);
    

    输出(好):

    cscript 24272956.js
     Use Cases
    

    样本输出(坏):

    cscript 24272956.js
    ..\data\24272956.nosuchfile: The system cannot locate the object specified.
    
    cscript 24272956.js
    no node found for //*[@id = 'Fullname']
    
    cscript 24272956.js
    ..\data\24272956.xml: End tag 'Body' does not match the start tag 'body'.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2012-05-03
      • 2015-03-20
      • 1970-01-01
      相关资源
      最近更新 更多