XPath - 替换元素的名称
XPath - replace element's name
样本html:
<div>
<button class="show-more-button" data-url="https://www.example.com/">
View More
</button>
</div>
我需要一个抓取项目来将 BUTTON 元素解释为 A 并将 data-url 解释为 href:
<div>
<A class="show-more-button" href="https://www.example.com/">
View More
</button>
</div>
这是我到目前为止的尝试。尝试使用替换和翻译:
//DIV/BUTTON[translate(DIV, "BUTTON", "A")][translate(DIV, "data-url", "href")][contains(@class, "show-more-button")]
如何实现?
像这样应用 XSLT,您可以转换 HTML 并将 button
转换为 a
并将 @data-url
转换为 @href
:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="button">
<a>
<xsl:apply-templates select="@*|node()"/>
</a>
</xsl:template>
<xsl:template match="@data-url">
<xsl:attribute name="href">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
如果您只想转换 button
个元素的 @data-url
,则将通用匹配表达式 @data-url
调整为 button/@data-url
。
样本html:
<div>
<button class="show-more-button" data-url="https://www.example.com/">
View More
</button>
</div>
我需要一个抓取项目来将 BUTTON 元素解释为 A 并将 data-url 解释为 href:
<div>
<A class="show-more-button" href="https://www.example.com/">
View More
</button>
</div>
这是我到目前为止的尝试。尝试使用替换和翻译:
//DIV/BUTTON[translate(DIV, "BUTTON", "A")][translate(DIV, "data-url", "href")][contains(@class, "show-more-button")]
如何实现?
像这样应用 XSLT,您可以转换 HTML 并将 button
转换为 a
并将 @data-url
转换为 @href
:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="button">
<a>
<xsl:apply-templates select="@*|node()"/>
</a>
</xsl:template>
<xsl:template match="@data-url">
<xsl:attribute name="href">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
如果您只想转换 button
个元素的 @data-url
,则将通用匹配表达式 @data-url
调整为 button/@data-url
。