首页 > 解决方案 > 需要删除创建的空元素并添加列表

问题描述

嗨,我为单个 XSL 提供了三种类型的输入。我已经为这两种类型编写了 XSL。但我对第三种类型感到震惊

输入类型 1 的 XML 文件:

<Description>School</Description>

输入类型 2 的 XML 文件:

<Description>School
<Text>Time</Text></Description>

输入类型 3 的 XML 文件:

<Description>School
<List type="bullet">
<ListItem>Date</ListItem>
<ListItem>Time</ListItem>
</List>
<Text>Push</Text></Description>

我已经为类型 1 和类型 2 尝试了 XSL,它运行良好:

<xsl:template match="Description">
        <def>
            <para>
                <xsl:value-of select="normalize-space(node()[1])"/>
            <def>
                <xsl:value-of select="Text"/>
            </def></para>
        </def>
    </xsl:template>

但是对于类型 1,正在创建空元素,我需要覆盖所有元素。

例外输出将是:

   <def>
        <para>School
        <list>
            <listitem><para>Date</para></listitem>
            <listitem><para>Time</para></listitem>
        </list>
            <def>Push</def>
        </para>
    </def>

我还想删除类型 1 和类型 2 的输出中的空元素。

标签: xmlxsltxslt-2.0

解决方案


XSLT 的正常用途是设置模板处理要转换的节点,每个模板通常处理特定元素或节点类型的转换,并用于xsl:apply-templates继续处理子节点或其他相关节点:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

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

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

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

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

您可以在https://xsltfiddle.liberty-development.net/ejivdGL/0、https://xsltfiddle.liberty-development.net/ejivdGL/1、https://xsltfiddle.liberty为您的三个示例设置它-development.net/ejivdGL/2


推荐阅读