XSLT 删除最后一个重复的空段

问题描述 投票:0回答:1

我的 xml 看起来像这样

<a>
 <b>b</b>
 <c>
    <d>
     <d1></d1>
     <d2></d2>
    </d>
    <d>
     <d1>1</d1>
     <d2>2</d2>
    </d>    
    <d>
     <d1>3</d1>
     <d2>4</d2>
    </d>
    <d>
     <d1></d1>
     <d2></d2>
    </d>    
 </c>
 
 </a>

我希望输出保持第一个空段(这里

<d> <d1></d1> <d2></d2> </d>
)不变,并删除最后一个空段(
<d> <d1></d1> <d2></d2>  </d>
),如下

<a>
 <b>b</b>
 <c>
    <d>
     <d1></d1>
     <d2></d2>
    </d>
    <d>
     <d1>1</d1>
     <d2>2</d2>
    </d>    
    <d>
     <d1>3</d1>
     <d2>4</d2>
    </d>

 </c>
 
 </a>

我尝试了以下xsl,但输出是这样的

 <a>
 <b>b</b>
 <c>
    <d/>
    <d>
     <d1>1</d1>
     <d2>2</d2>
    </d>    
    <d>
     <d1>3</d1>
     <d2>4</d2>
    </d>

 </c>
 
 </a>

我需要输出中第一个空段的空子标签。非常感谢 xsl 上的任何解决方案。

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" 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[last()]]">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="@* | node()" />
        </xsl:element>
    </xsl:template>
    <xsl:template match="@*[not[last()]]">
        <xsl:attribute name="{local-name()}">
            <xsl:value-of select="." />
        </xsl:attribute>
    </xsl:template>

    <xsl:template match="*[last()][normalize-space() = '']"/>   
    <xsl:template match="text() | comment() | processing-instruction()">
        <xsl:copy />
    </xsl:template>
</xsl:stylesheet>
xml xslt
1个回答
0
投票

尝试类似的事情

 <xsl:template match="c/d[not(*[.!= ''])][last()]"/>

删除

d
的最后一个
c
子节点,该子节点只有空子节点。然而,如果只有一个这样的元素(即
d
为 1),那么这会删除这样的
last()
元素,所以也许你更想要

 <xsl:template match="c/d[not(*[.!= ''])][position() > 1 and position() = last()]"/>

当然,所有这些都与身份转换设置一起,因此通过设置模板以声明方式如 XSLT 3 中的

<xsl:mode on-no-match="shallow-copy"/>
或以前版本的 XSLT (1, 2)

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>
© www.soinside.com 2019 - 2024. All rights reserved.