【问题标题】:How to extract links from .js file using XSLT如何使用 XSLT 从 .js 文件中提取链接
【发布时间】:2014-02-27 20:09:45
【问题描述】:

我有一个 .js 文件。这是一个带有如下文本的 javascript 文件。我想提取所有的 href URL 并将它们添加到循环内的变量中以进行进一步处理。我怎样才能做到这一点?非常感谢。

 document.write('<tr bgcolor="#6691BC">'); document.write('<td
 width="15" height="25">&nbsp;</td>'); document.write('<td width="690"
 height="25" class="headertext">');

 document.write('<a href="../myspace.com/index.html" class="headerLink"
 style="color: #ffffff;">My Space</a>&nbsp;&nbsp;|&nbsp;&nbsp;');

 document.write('<a href="../technotes.com/index.html"
 class="headerLink" style="color: #ffffff;">Tech
 Notes</a>&nbsp;&nbsp;|&nbsp;&nbsp;');

 document.write('<td width="15" height="25">&nbsp;</td>');
 document.write('</tr>');

【问题讨论】:

  • XSLT 不是 Javascript 解析器,任意 JS 都不是有效的 XML。
  • XSLT 可以解决河内的塔,所以我不认为子字符串匹配超出了它的能力,但这并不容易或漂亮......
  • -1 XSLT 仅适用于 XML。

标签: javascript xslt


【解决方案1】:

我会采用不同的方法 - 首先将您的 html 转换为单个 xhtml 字符串(注意缺少的 &lt;/td&gt;,而 &amp;amp; 需要转义为 &amp;amp;

var xhtml = [
'<tr bgcolor="#6691BC">', 
  '<td width="15" height="25">&amp;nbsp;</td>',
  '<td width="690" height="25" class="headertext">',
    '<a href="../myspace.com/index.html" class="headerLink" style="color: #ffffff;">My Space</a>&amp;nbsp;&amp;nbsp;|',
    '<a href="../technotes.com/index.html" class="headerLink" style="color: #ffffff;">Tech Notes</a>'
  '</td>',
  '<td width="15" height="25"><a id="JustAnAnchor">Anchor</a></td>',
'</tr>'].join("");

document.write(xhtml);

然后您需要 solve the challenge 在 javascript 中应用 xslt 转换。

以下 xslt 将从所有 &lt;a href&gt; 标记中提取 hrefs 并将它们转储到逗号分隔的列表中,然后您可以在 javascript 中使用该列表(应该不需要 remove the extraneous last trailing comma

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="/">
        <xsl:apply-templates select="//a[@href]"></xsl:apply-templates>
    </xsl:template>

    <xsl:template match="a">'<xsl:value-of select="@href"/>',</xsl:template>
</xsl:stylesheet>

输出:

'../myspace.com/index.html','../technotes.com/index.html',

【讨论】:

    【解决方案2】:

    XSLT 无法轻松解析 Javascript。这是不适合这项工作的工具。

    以下是您可以采用的一些方法:

    (1) 运行 javascript,捕获生成的文档,然后在其上使用 XSLT。如果文档不是格式良好的 XML,这可能会很麻烦。

    (2) 使用正则表达式,例如grep, perl -e, Javascript 匹配函数

    (3) 运行 javascript,然后使用 document.querySelectorAll('*[href]') 获取所有带有 href 的元素并在那里工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 2022-12-14
      • 2022-08-18
      • 2021-08-14
      • 1970-01-01
      相关资源
      最近更新 更多