2013-05-07 76 views
2

我想提取html页面中<head>标记元素之间的所有内容。包括链接标签和脚本标签。使用XSLT提取HTML元素

假设下面的源代码是一个片段,它将成为完整的html文档的一部分。

来源:

... 
<head> 
<link rel="stylesheet" href="style.css" 
    type="text/css" media="handheld" /> 

<link rel="stylesheet" href="style.css" 
    type="text/css" media="handheld" /> 

<script type="text/javascript" src="main.js"></script> 
<script type="text/javascript" src="second.js"></script> 
</head> 
... 

XSLT:

<xsl:output method="xml" encoding="utf-8" indent="no"/> 

<xsl:template match="/"> 
    <xsl:copy-of select="link"/> 
</xsl:template> 

这工作正常,如果只有一个标签,我试图让。有没有一种方法可以处理所有事情,只有“头”标签之间的所有内容。

我预计会是输出:

<link rel="stylesheet" href="style.css" 
    type="text/css" media="handheld" /> 

<link rel="stylesheet" href="style.css" 
    type="text/css" media="handheld" /> 

<script type="text/javascript" src="main.js"></script> 
<script type="text/javascript" src="second.js"></script> 
+0

您能否提供一个更完整的源文档示例,以及您期望的输出示例? – 2013-05-07 17:38:30

+0

通常,只能在符合XML的数据(如XHTML)上使用XSL。如果你的输入不是XHTML,你可能会在某个时候得到解析异常。 – 2013-05-07 22:53:53

回答

2

您需要使用XSL 恒等变换

<xsl:template match="@*|node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

与防止一切的输出,你不想要一个模板一起。

<xsl:template match="/"> 
    <xsl:apply-templates select="html/head"/> 
</xsl:template> 

第二个模板,更加具体,将匹配根,然后将样式表应用到<head>标签的内容。身份转换将输出所需的标签。

+0

+1,比依靠''更加优雅。 – ABach 2013-05-08 00:19:36

0

您需要使用 '的xsl:for-每个' 语句

<xsl:template match="/"> 
     <xsl:for-each select="head/*"> 
     <xsl:copy-of select="."/> 
     </xsl:for-each> 
    </xsl:template> 
0

我想你可以使用<xsl:for-each>元素来选择每一个XML元素一个指定的节点集。

只需循环遍历head标签中的所有元素,然后使用xsl-current()函数以像这样的方式获取每个元素的值; <xsl:value-of select="current()"/>