XSLT替换null元素和属性值

时间:2013-05-04 04:36:54

标签: xslt attributes replace null element

在下面的XSLT中,我正在检查以下内容

  1. 如果element为null,则替换然后将其替换为另一个元素的值。
  2. 如果该元素的属性为null,则将其替换为常量值。
  3. 1正在运行,但是2不是。

    对于2我尝试了两件事:

    首先,使用xsl:if条件不起作用。 它正在添加具有相同节点名称的新节点,而不是向属性插入值。

    其次我试图使用模板。那也行不通。 它完全消除了节点并使用值将属性添加到父节点。

    此外,是否可以采用不同的方式或更好的方式。

    XSLT

      <xsl:template match="//ns0:Cedent/ns0:Party/ns0:Id">
        <xsl:if test="//ns0:Cedent/ns0:Party/ns0:Id = ''">
          <xsl:copy>
            <xsl:value-of select="//ns0:Broker/ns0:Party/ns0:Id"/>
          </xsl:copy>
        </xsl:if>
        <!--<xsl:if test="//ns0:Cedent/ns0:Party/ns0:Id[@Agency = '']">
          <xsl:copy>
            <xsl:attribute name="Agency">Legacy</xsl:attribute>
            <xsl:value-of select="'Legacy'"/>
          </xsl:copy>
        </xsl:if>-->
      </xsl:template>
    
      <xsl:template match="//ns0:Cedent/ns0:Party/ns0:Id[@Agency = '']">
        <xsl:attribute name="Agency">Legacy</xsl:attribute>
      </xsl:template>
    

    输入

    <ns0:Testing>
      <ns0:Cedent>
        <ns0:Party>
          <ns0:Id Agency=""></ns0:Id>
          <ns0:Name>Canada</ns0:Name>
        </ns0:Party>
      </ns0:Cedent>
      <ns0:Broker>
        <ns0:Party>
          <ns0:Id Agency="Legacy">292320710</ns0:Id>
          <ns0:Name>Spain</ns0:Name>
        </ns0:Party>
      </ns0:Broker>
    </ns0:Testing>
    

    输出

    <ns0:Testing>
        <ns0:Cedent>
          <ns0:Party>
            <ns0:Id Agency="Legacy">292320710</ns0:Id>
            <ns0:Name>Canada</ns0:Name>
          </ns0:Party>
        </ns0:Cedent>
    </ns0:Testing>
    

1 个答案:

答案 0 :(得分:1)

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:ns0="some_namespace_uri"
>
  <xsl:output indent="yes" />

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

  <xsl:template match="ns0:Cedent/ns0:Party/ns0:Id[. = '']">
    <xsl:copy>
      <xsl:apply-templates select="@*" />
      <xsl:apply-templates select="
        ../../following-sibling::ns0:Broker[1]/ns0:Party/ns0:Id/node()
      " />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="ns0:Cedent/ns0:Party/ns0:Id/@Agency[. = '']">
    <xsl:attribute name="Agency">Legacy</xsl:attribute>
  </xsl:template>

</xsl:stylesheet>

给你

<Testing xmlns="some_namespace_uri">
  <Cedent>
    <Party>
      <Id Agency="Legacy">292320710</Id>
      <Name>Canada</Name>
    </Party>
  </Cedent>
  <Broker>
    <Party>
      <Id Agency="Legacy">292320710</Id>
      <Name>Spain</Name>
    </Party>
  </Broker>
</Testing>

注意:

  • 如果您根本不想要输出中的<Broker>元素,请添加一个空模板:

    <xsl:template match="ns0:Broker" />
    
  • 模板中的匹配表达式不需要从根节点开始。

  • 样式表的作用是复制输入,只需要进行一些更改,就像这一样,应始终以身份模板开头。
相关问题