解析XML时xsl中的条件语句

时间:2016-04-07 05:45:56

标签: xml csv xslt xslt-1.0 xslt-2.0

我正在尝试使用XSL将XML文件转换为CSV但在应用条件语句时遇到问题。 我有以下XML文件。

<?xml version="1.0" encoding="ISO-8859-1"?>
<document>
    <User>
        <userid>2000</userid>
        <fruit>
           <FieldValue>
               <Name>Apple</Name>
               <value>500</value>
           </FieldValue>

           <FieldValue>
               <Name>Orange</Name>
               <value>1000</value>
            </FieldValue>

            <FieldValue>
              <Name>Pineapples</Name>
              <value>500</value>
            </FieldValue>
        </fruit>
        <biometric>
            <FieldValue>
              <Name>Weight</Name>
              <value>50lb</value>
            </FieldValue>
        <biometric>
   </User>
</document>

我需要为每个用户提供以下常量标题格式的输出:

userid,Apple,Avocardo,Orange,Pineapples,Height,Weight
2000,500,,1000,500,,50lb 

请注意,原始XML文件中缺少Avocardo和Height,它们将被指定为NULL或空值。 有人可以帮助为这个csv解析编写一个xsl吗?

1 个答案:

答案 0 :(得分:1)

解决方案的核心可以是(在2.0中)

<xsl:template match="User">
  <xsl:variable name="this" select="."/>
  <xsl:value-of select="userid"/>
  <xsl:for-each 
     select="'Apple','Avocardo','Orange','Pineapples','Height','Weight'">
   <xsl:value-of 
     select="concat(',', $this//FieldValue[Name=current()]/value)"/>
  </xsl:for-each>
  <xsl:text>&#xa;</xsl:text>
</xsl:template>