给出以下URL,如何确定路径的深度为几级?
https://example.com/{product}/
https://example.com/(product}/{vendor}
https://example.com/{product}/{vendor}/{location}
这些是可变字符串:product
,vendor
,location
我有以下代码可用于具有恒定值的路径:
<xsl:variable name="itemURL">
<xsl:value-of select="sitemap:loc"/>
</xsl:variable>
<td>
<xsl:if test="contains($itemURL, '/Section/')">
<xsl:attribute name="class">section</xsl:attribute>
</xsl:if>
<xsl:if test="contains($itemURL, '/Category/')">
<xsl:attribute name="class">category</xsl:attribute>
</xsl:if>
<xsl:if test="contains($itemURL, '/Product/')">
<xsl:attribute name="class">product</xsl:attribute>
</xsl:if>-->
<a href="{$itemURL}">
<xsl:value-of select="sitemap:loc"/>
</a>
</td>
这些简单常量的CSS:
.section {
font-weight: 600;
}
.category {
font-weight: 500;
padding-left: 15px;
}
.product {
padding-left: 30px;
font-style: italic;
}
我想要做的是稍后在URL列表更深入时缩进或添加项目符号或带有CSS的内容。基本上,我想嵌套它,以便人类阅读。我必须在这里使用正则表达式,还是有一种更好的方法是纯XSLT?
答案 0 :(得分:1)
考虑以下示例:
XML
<root>
<URL>https://example.com</URL>
<URL>https://example.com/product</URL>
<URL>https://example.com/product/vendor</URL>
<URL>https://example.com/product/vendor/location</URL>
</root>
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/root">
<results>
<xsl:for-each select="URL">
<xsl:variable name="path" select="substring-after(., 'https://example.com')" />
<xsl:variable name="slashes" select="translate($path, translate($path, '/', ''), '')"/>
<result>
<xsl:value-of select="translate($slashes, '/', '•')"/>
<xsl:value-of select="$path"/>
</result>
</xsl:for-each>
</results>
</xsl:template>
</xsl:stylesheet>
结果
<?xml version="1.0" encoding="UTF-8"?>
<results>
<result/>
<result>•/product</result>
<result>••/product/vendor</result>
<result>•••/product/vendor/location</result>
</results>
或者:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/root">
<results>
<xsl:for-each select="URL">
<xsl:variable name="path" select="substring-after(., 'https://example.com')" />
<xsl:variable name="count-slashes" select="string-length(translate($path, translate($path, '/', ''), ''))"/>
<result>
<xsl:attribute name="class">
<xsl:choose>
<xsl:when test="$count-slashes=1">product</xsl:when>
<xsl:when test="$count-slashes=2">vendor</xsl:when>
<xsl:when test="$count-slashes=3">location</xsl:when>
<xsl:otherwise>URL</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:value-of select="."/>
</result>
</xsl:for-each>
</results>
</xsl:template>
</xsl:stylesheet>
结果
<?xml version="1.0" encoding="UTF-8"?>
<results>
<result class="URL">https://example.com</result>
<result class="product">https://example.com/product</result>
<result class="vendor">https://example.com/product/vendor</result>
<result class="location">https://example.com/product/vendor/location</result>
</results>