在XSLT中的选择性副本中插入节点

时间:2010-11-02 21:48:45

标签: xml xslt xslt-2.0

我正在过滤掉我的XSLT转换中的某些节点,剩下的就是如果缺少某个子元素,我需要插入一个元素。

这就是我所拥有的。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" >
<xsl:output method="xml" indent="yes"/>

  <xsl:template xpath-default-namespace="http://www.tempuri.org" match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template xpath-default-namespace="http://www.tempuri.org" match="SomeNode">
  </xsl:template>
  <xsl:template xpath-default-namespace="http://www.tempuri.org" match="TheNode[@type!='SomeType' and @type!='OtherType']">

<!-- If TheNode is missing a child element SomeElement, insert a blank SomeElement element -->

  </xsl:template>

</xsl:stylesheet>

有人可以提出最好的解决方法吗?

感谢。

1 个答案:

答案 0 :(得分:3)

此转化

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xpath-default-namespace="http://www.tempuri.org" >
 <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="SomeNode">
  </xsl:template>
  <xsl:template match=
      "TheNode[not(@type = ('SomeType','OtherType')) and not(SomeElement)]">
    <xsl:copy>
     <xsl:apply-templates select="@*"/>
     <SomeElement xmlns="http://www.tempuri.org"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

应用于此XML文档

<t xmlns="http://www.tempuri.org">
 <a>
  <b/>
  <SomeNode/>
  <TheNode type="x"/>
  <TheNode type="y">
   <SomeElement/>
  </TheNode>
 </a>
</t>

生成想要的正确结果

<t xmlns="http://www.tempuri.org">
   <a>
      <b/>
      <TheNode type="x">
         <SomeElement/>
      </TheNode>
      <TheNode type="y">
         <SomeElement/>
      </TheNode>
   </a>
</t>
相关问题