XSLT test on xsl:template



我有一个 xml 文件

<?xml version="1.0" encoding="UTF-8"?> 
<CategoriesList>
  <Category ID="1" >
    <Name ID="1395687" Value="Libelle1" langid="1"/>
    <Name ID="1395689" Value="" langid="3"/>
  </Category>
  <Category ID="2" >
    <Name ID="1395687" Value="" langid="1"/>
    <Name ID="1395689" Value="Libelle2" langid="3"/>
  </Category>
</CategoriesList>

我尝试使用 XSLT 文件做一个智能过滤器

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output  method="xml" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
    <xsl:apply-templates/>
</xsl:template>
<xsl:template match="CategoriesList">
    <xsl:apply-templates select="Category"/>
</xsl:template>
<xsl:template match="Category">
    <xsl:element name="Category">
        <xsl:attribute name="ID">
            <xsl:value-of select="@ID"/>
        </xsl:attribute>
        <xsl:apply-templates select="Name"/>
    </xsl:element>
</xsl:template>
<xsl:template match="Name[@langid=3]">
    <xsl:attribute name="Name">
        <xsl:value-of select="@Value"/>
    </xsl:attribute>
</xsl:template>

我可以过滤为仅采用 langid=3 的名称节点但我想要:如果 langid=3 的名称节点为空,则取 langid=1 的名称节点如果 langid=3 的命名节点不为空,则取 langid=3 的命名节点

我看到了

拜托,你能帮我吗

如果"空"表示 Value 属性为空,请尝试如下操作:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/CategoriesList">
    <xsl:copy>
        <xsl:apply-templates select="Category"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="Category">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:attribute name="Name">
            <xsl:choose>
                <xsl:when test="Name[@langid=3][string(@Value)]">
                    <xsl:value-of select="Name[@langid=3]/@Value"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="Name[@langid=1]/@Value"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:attribute>
    </xsl:copy>
</xsl:template> 
</xsl:stylesheet>

应用于您的输入示例,结果为:

<?xml version="1.0" encoding="UTF-8"?>
<CategoriesList>
  <Category ID="1" Name="Libelle1"/>
  <Category ID="2" Name="Libelle2"/>
</CategoriesList>

请注意,我们假设 langid 在每个类别中都是唯一的。

最新更新