首页 > 解决方案 > 判断XML标签是否包含元素的条件语句?(XSLT)

问题描述

我在下面有两个不同的 XML 文档:

XML 1

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<Match>
    <Trades>
        <Trade fruitId="apples"/>
    </Trades>
</Match> 

XML 2

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<Match2>
    <Properties>
        <foobar>123</foobar>
    </Properties>
    <Trades>
        <Trade vegetableId="eggplant"/>
    </Trades>
</Match2>

我想创建一个 XSLT 文档,该文档基本上采用 fruitId, 或中的值vegetableId,具体取决于哪个可用。XSLT 应该同时满足 XML1 和 XML2。

我不知道如何处理这个问题,我是否应该创建一个 if 语句来检查这个 Trades 标签是否包含一个vegetedId 或FruitId。我有点迷失在这里。这是我到目前为止想出的。

我的 XSLT 尝试

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
     <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />

     <xsl:template match="/">
         <xsl:apply-templates/>
     </xsl:template>

     <xsl:template match="Trades/Trade">
         <xsl: if test = "(contains(@fruitId, 'somevalue'))">
              <xsl:value-of select="@fruitId"/>
         </xsl:if>
         <xsl: if test = "(contains(@vegetableId, 'somevalue'))">
              <xsl:value-of select="@vegetableId"/>
         </xsl:if>
     </xsl:template>

</xsl:stylesheet>

我知道我的 contains 语句内部有“somevalue”,这不是我正在运行的实际代码,而是我想尝试的想法,尽管我不知道如何处理。

此外, <Match>不同于<Match2>.

请指教。谢谢!

标签: xmlxsltxml-parsingxslt-1.0xslt-2.0

解决方案


You could simply use something like this. Depending on the document you are passing to the transformation, only one element of the concat() function will be non-empty, so effectively only one value will be present in the output.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
     <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
     <xsl:strip-space elements="*" />

     <xsl:template match="Trades/Trade">
       <output><xsl:value-of select="concat(@fruitId,@vegetableId)"/></output>
     </xsl:template>
     
     <xsl:template match="text()"/>

</xsl:stylesheet>

See it working here (I merged the two files together to test): https://xsltfiddle.liberty-development.net/ei5R4up


推荐阅读