通过XSLT 2.0在html中生成ID和引用

问题描述 投票:1回答:1

请帮我。我在生成Id时遇到问题并在其数据匹配时引用它。

INPUT:这是我的输入信息。

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <table>
        <tr><td>para 1</td></tr>
        <tr><td>para 2</td></tr>
        <tr><td>para 3</td></tr>
    </table>

    <para>para 1</para>
    <para>para 2</para>
    <para>para 3</para>
</root>

XSLT:我现在正在使用它进行转换。

<?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" 
    exclude-result-prefixes="xs" version="2.0">
    <xsl:strip-space elements="*"/>
    <xsl:output method="xhtml"/>

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

    <xsl:template match="root">
        <html>
            <head>First HTML</head>
            <body>
                <xsl:apply-templates/>
            </body>
        </html>
    </xsl:template>

    <xsl:template match="para">
        <p>
            <xsl:attribute name="id" select="generate-id(.)"/>
            <xsl:apply-templates/>
        </p>
    </xsl:template>

    <xsl:template match="td">
        <xsl:variable name="cur" select="."/>
        <xsl:copy>
            <a href="{concat('#',generate-id(para[. = $cur]))}">
                <xsl:apply-templates/>
            </a>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

当前输出:通过转换我得到了这个结果。

<?xml version="1.0" encoding="UTF-8"?><html>
   <head>First HTML</head>
   <body>
      <table>
         <tr>
            <td>
               <a href="#">para 1</a>
            </td>
         </tr>
         <tr>
            <td>
               <a href="#">para 2</a>
            </td>
         </tr>
         <tr>
            <td>
               <a href="#">para 3</a>
            </td>
         </tr>
      </table>
      <p id="d1e12">para 1</p>
      <p id="d1e14">para 2</p>
      <p id="d1e16">para 3</p>
   </body>
</html>

期望的输出:当td和p的文本匹配时应该是参考。

<?xml version="1.0" encoding="UTF-8"?><html>
   <head>First HTML</head>
   <body>
      <table>
         <tr>
            <td>
               <a href="#d1e12">para 1</a>
            </td>
         </tr>
         <tr>
            <td>
               <a href="#d1e14">para 2</a>
            </td>
         </tr>
         <tr>
            <td>
               <a href="#d1e16">para 3</a>
            </td>
         </tr>
      </table>
      <p id="d1e12">para 1</p>
      <p id="d1e14">para 2</p>
      <p id="d1e16">para 3</p>
   </body>
</html>

谢谢

xml xpath xslt-2.0
1个回答
1
投票

您需要选择para元素,其路径类似于//para,例如<a href="{concat('#',generate-id(//para[. = $cur]))}">可以简化为<a href="#{generate-id(//para[. = $cur])}">

然而,定义密钥更有效:<xsl:key name="para-content" match="para" use="."/>然后使用<a href="#{generate-id(key('para-content', .))}">...

© www.soinside.com 2019 - 2024. All rights reserved.