首页 > 解决方案 > (XSLT) 使用属性值对标签进行编号

问题描述

所以我得到了例如这个 xhtml 文件(https://xsltfiddle.liberty-development.net/bdxtqF):

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

</head>
<body>
    <p>first line</p>
    <p>second line</p>
    <p>third line</p>
    <p>forth line</p>
    <p>fifth line</p>
</body>

我想为 p 标签编号,但它们的值应被视为 id 属性。我知道您可以使用 xsl:number 但我只知道如何在节点内编号:

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xpath-default-namespace="http://www.w3.org/1999/xhtml"
    exclude-result-prefixes="#all"
    version="3.0">

   <xsl:template match="body">
       <test>
       <xsl:apply-templates />
       </test>
   </xsl:template>

   <xsl:template match="p">
        <p><xsl:number/>. <xsl:apply-templates /></p>
   </xsl:template>

</xsl:stylesheet>

但我想要的结果应该是这样的

<?xml version="1.0" encoding="UTF-8"?>



<test>
    <p id="1">first line</p>
    <p id="2">second line</p>
    <p id="3">third line</p>
    <p id="4">forth line</p>
    <p id="5">fith line</p>
</test>

如何在标签内创建属性名称并开始对其中的值进行编号?提前致谢!

标签: xmlxsltxhtml

解决方案


您可以xsl:attribute在此处使用来创建属性

<xsl:template match="p">
 <p>
   <xsl:attribute name="id">
     <xsl:number />
   </xsl:attribute>
   <xsl:apply-templates />
 </p>
</xsl:template>

或者,如果您添加strip-space到样式表中,您可以使用position()

<xsl:strip-space elements="*" />

<xsl:template match="body">
  <test>
    <xsl:apply-templates />
  </test>
</xsl:template>

<xsl:template match="p">
  <p id="{position()}">
    <xsl:apply-templates />
  </p>
</xsl:template>

没有strip-spacexsl:apply-templates选择空白文本节点,这会影响位置。请注意,如果body除此之外还有其他元素,p则不会给您预期的结果。在这种情况下你可以这样做<xsl:apply-templates select="p" />,但这会假设你想忽略其他元素。


推荐阅读