仅当源中存在值时才创建标记

时间:2014-03-12 14:47:22

标签: java xslt

例如:

<a>
<b>
    <aaa>val</aaa>
    <bbb></bbb>
</b>
</a>

我想要一个xslt,它只会在源代码中包含值时创建aaa,bbb,ccc标记。

直到现在我用过:

<aaa><xsl:value-of select="//aaa"/></aaa>
<bbb><xsl:value-of select="//bbb"/></bbb>
<ccc><xsl:value-of select="//ccc"/></ccc>

这显然不太好。

3 个答案:

答案 0 :(得分:2)

对你想要达到的目标做出一些假设(你没有这么说,我很害怕),下面的解决方案应该有效。

<强>输入

<a>
  <b>
    <aaa>val</aaa>
    <bbb></bbb>
  </b>
</a>

样式表非常动态,即不依赖于实际的元素名称,但它依赖于XML文档的结构

样式表(“动态”)

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output method="xml" indent="yes"/>
   <xsl:strip-space elements="*"/>

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

   <xsl:template match="/*/*/*[not(text())]"/>
   <xsl:template match="/*/*/*[text()]">
       <xsl:copy-of select="."/>
   </xsl:template>

</xsl:stylesheet>

另一方面,如果事先知道元素名称并且不更改,则可以在样式表中使用它们:

样式表(“静态”元素名称)

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output method="xml" indent="yes"/>
   <xsl:strip-space elements="*"/>

   <xsl:template match="/a|b">
       <xsl:copy>
           <xsl:apply-templates/>
       </xsl:copy>
   </xsl:template>

   <xsl:template match="aaa|bbb">
      <xsl:choose>
          <xsl:when test="text()">
              <xsl:copy-of select="."/>
          </xsl:when>
          <xsl:otherwise/>
      </xsl:choose>
   </xsl:template>

</xsl:stylesheet>

<强>输出

<?xml version="1.0" encoding="UTF-8"?>
<a>
   <b>
      <aaa>val</aaa>
   </b>
</a>

答案 1 :(得分:1)

您可以为要省略的元素创建一个空模板,并为其他元素创建一个标识转换模板:

<xsl:template match="aaa[string-length(text()) = 0]" />
<xsl:template match="bbb[string-length(text()) = 0]" />

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
</xsl:template>

答案 2 :(得分:1)

与其他答案类似,这不依赖于名称或结构;它只是删除不包含任何子元素或文本的元素。就像之前提到的那样,很难说出你真正想要的是什么输出。

XSLT 1.0

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

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[not(*|text())]"/>

</xsl:stylesheet>

<强>输出

<a>
   <b>
      <aaa>val</aaa>
   </b>
</a>
相关问题