当兄弟元素任意存在时,XSLT按顺序创建元素?

时间:2017-08-08 21:17:30

标签: xml xslt

假设您有一个包含内容模型的元素,如下所示:

<!ELEMENT wrapper (a*,b*,c*,d*,e*,f*,g*,h*,i*,j*,k*,l*,m*,n*,o*,p*,q*,r*,s*,t*,u*,v*,w*,x*,y*,z*)>

换句话说,在一个包装元素中,有一个可以任意存在的子元素的指定顺序。

您需要在包装器中创建一个新元素(例如m),同时保留已存在的元素,并确保输出符合内容模型。

这是一种解决方案:

<xsl:template match="@*|node()">
  <xsl:sequence select="."/>
</xsl:template>

<xsl:template match="wrapper">
  <xsl:copy>
    <xsl:apply-templates select="a,b,c,d,e,f,g,h,i,j,k,l,m"/>
    <m>This is new</m>
    <xsl:apply-templates select="n,o,p,q,r,s,t,u,v,w,x,y,z"/>
  </xsl:copy>
</xsl:template>

但是,此解决方案将删除包装器元素中的所有空格,注释或处理指令。我提出了一些解决方案,不要放弃这些东西,但没有我满意的。

这个问题最优雅的解决方案是什么?它不会丢弃节点? XSLT 3和模式感知解决方案都很好。

以下是一些示例输入和输出:

<!-- Input -->
<wrapper/>

<!-- Output -->
<wrapper><m>This is new</m></wrapper>

<!-- Input -->
<wrapper><a/><z/></wrapper>

<!-- Output -->
<wrapper><a/><m>This is new</m><z/></wrapper>

<!-- Input -->
<wrapper><m/></wrapper>

<!-- Output -->
<wrapper><m/><m>This is new</m></wrapper>

<!-- Input -->
<wrapper>
  <a/>
  <!-- put m here -->
  <z/>
</wrapper>

<!-- Output -->
<!-- NB: The comment and whitespace could come after the inserted element instead. This case is ambiguous -->
<wrapper>
  <a/>
  <!-- put m here --><m>This is new</m>
  <z/>
</wrapper>

<!-- Input -->
<wrapper>
  <a/>
  <b/>
  <c/>
  <n/>
  <o/>
  <!-- p is not here -->
  <?do not drop this?>
</wrapper>

<!-- Output -->
<wrapper>
  <a/>
  <b/>
  <c/><m>This is new</m>
  <n/>
  <o/>
  <!-- p is not here -->
  <?do not drop this?>
</wrapper>

插入元素周围的非元素节点在之前或之后出现并不重要,只是它们不会被删除,并且它们相对于原始元素的顺序会被保留。

1 个答案:

答案 0 :(得分:5)

这是你可以看到它的一种方式:

XSLT 2.0

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

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

<xsl:template match="wrapper">
    <xsl:variable name="all" select="node()"/>
    <xsl:variable name="middle" select="(n,o,p,q,r,s,t,u,v,w,x,y,z)[1]"/>
    <xsl:variable name="i" select="if($middle) then count($all[. &lt;&lt; $middle]) else count($all)"/>
    <xsl:variable name="new">
        <m>This is new</m>
    </xsl:variable>
    <xsl:copy>
        <xsl:apply-templates select="insert-before($all, $i+1, $new) "/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

或者,如果您愿意:

<xsl:template match="wrapper">
    <xsl:variable name="all" select="node()"/>
    <xsl:variable name="middle" select="(a,b,c,d,e,f,g,h,i,j,k,l,m)[last()]"/>
    <xsl:variable name="i" select="if($middle) then index-of($all/generate-id(), generate-id($middle)) else 0"/>
    <xsl:variable name="new">
        <m>This is new</m>
    </xsl:variable>
    <xsl:copy>
        <xsl:apply-templates select="insert-before($all, $i+1, $new) "/>
    </xsl:copy> 
</xsl:template>