首页 > 解决方案 > XSLT 选择节点而不丢失属性

问题描述

我正在尝试对 xml 标签进行 xslt 转换,输出按预期进行,但所有属性值都被修剪掉了。我希望需要应用所有属性,但需要像属性名称一样修改特定属性。

请在下面找到示例。

<section>
  <line number='1' style='none' bold='true' size='10pt'>Line 1</line>
  <line number='2' bold='true' >Line 2</line>
  <line number='3' style='none' bold='true' size='10pt' color='red'>Line 3</line>
</section>

我想转换为

<div>
      <p num='1' style='none' bold='true' size='10pt'>Line 1</p>
      <p num='2' b='true' >Line 2</p>
      <p num='3' style='none' bold='true' size='10pt' color='red'>Line 3</p>
</div>

这是我到目前为止写的例子。但这很复杂,因为我不能假设应用了哪个属性,所以我不想明确给出属性的名称。

<xsl:template match="section"><div use-attribute-sets="default"><xsl:apply-templates select="node()"/></div></xsl:template>

<xsl:template match="p"><p use-attribute-sets="default"><xsl:apply-templates select="node()"/></p></xsl:template>

        <xsl:attribute-set name="default">
            <xsl:attribute name="number"><xsl:value-of select="@num"/></xsl:attribute>
            <xsl:attribute name="style"><xsl:value-of select="@style"/></xsl:attribute>
            <xsl:attribute name="b"><xsl:value-of select="@bold"/></xsl:attribute>
            <xsl:attribute name="size"><xsl:value-of select="@size"/></xsl:attribute>
            <xsl:attribute name="color"><xsl:value-of select="@color"/></xsl:attribute>
        </xsl:attribute-set>

标签: javaxmlxslt

解决方案


如果您想在默认情况下复制所有现有属性,但有一些例外,您可以像以下代码一样实现:

<xsl:template match="*"> <!-- This matches all nodes. Note that specific templates have higher priority and will hit earlier (You can probably use your match="p" or "line") -->
    <xsl:apply-templates select="@*"/> <!-- Default value if no select is given is '*' so no attributes would be hit -->
</xsl:template>

<xsl:template match="@*"> <!-- Match all the attributes so you can copy them -->
    <xsl:copy/>
</xsl:template>

<xsl:template match="@bold"> <!-- Note that this will hit instead of @* because its more specific as described above -->
    <xsl:attribute name="b" select="."/>
</xsl:template>
<!-- Here you can specify more of such attribute matches if needed -->

推荐阅读