2
如何使用xsl转换替换xml中的属性,具体取决于其值。 例如,如果有这样的xmlxml属性替换xslt
<Text Style='style1'>
...
</Text>
其转换为
<Text Font='Arial' Bold='true' Color='Red'>
...
</Text>
对于类型= '蓝紫魅力'设置另一个属性和值,例如字体= '三世' 斜体=”真正'。
如何使用xsl转换替换xml中的属性,具体取决于其值。 例如,如果有这样的xmlxml属性替换xslt
<Text Style='style1'>
...
</Text>
其转换为
<Text Font='Arial' Bold='true' Color='Red'>
...
</Text>
对于类型= '蓝紫魅力'设置另一个属性和值,例如字体= '三世' 斜体=”真正'。
一个可行的方法:使用属性集。这个样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:attribute-set name="style1">
<xsl:attribute name="Font">Arial</xsl:attribute>
<xsl:attribute name="Bold">true</xsl:attribute>
<xsl:attribute name="Color">Red</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="style2">
<xsl:attribute name="Font">Sans</xsl:attribute>
<xsl:attribute name="Italic">true</xsl:attribute>
</xsl:attribute-set>
<xsl:template match="Text[@Style='style1']">
<xsl:copy use-attribute-sets="style1">
<xsl:copy-of select="@*[name()!='Style']"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="Text[@Style='style2']">
<xsl:copy use-attribute-sets="style2">
<xsl:copy-of select="@*[name()!='Style']"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
有了这个输入:
<root>
<Text Style='style1'></Text>
<Text Style='style2'></Text>
</root>
输出:
<Text Font="Arial" Bold="true" Color="Red"></Text>
<Text Font="Sans" Italic="true"></Text>
其他方式:内联 “属性设置”。此样式表:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my"
exclude-result-prefixes="my">
<xsl:output indent="yes"/>
<my:style1 Font="Arial" Bold="true" Color="Red"/>
<my:style2 Font="Sans" Italic="true"/>
<xsl:template match="Text[@Style]">
<xsl:copy>
<xsl:copy-of select="document('')/*/my:*
[local-name()=current()/@Style]/@*"/>
<xsl:copy-of select="@*[name()!='Style']"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
您将需要某种规则来将样式从一种转换为另一种。假设你正在输入html,你需要类似的东西。
<xsl:template match="@* | node()">
<xsl:choose>
<xsl:when test="local-name() = 'Style'">
<xsl:apply-templates select="." mode="Style" />
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="@Style" mode="Style">
<xsl:choose>
<xsl:when test="node() = 'style1'">
<xsl:attribute name="Font">Arial</xsl:attribute>
<xsl:attribute name="Bold">true</xsl:attribute>
<xsl:attribute name="Color">Red</xsl:attribute>
</xsl:when>
<xsl:when test="node() = 'style2'">
<xsl:attribute name="Font">Sans</xsl:attribute>
<xsl:attribute name="Bold">true</xsl:attribute>
</xsl:when>
</xsl:choose>
</xsl:template>