如何解决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>
解决方法
如果您要默认复制所有现有属性,但有些例外,可以使用以下代码来实现:
<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 -->
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。