从源XML中获取nil值

问题描述:

我做了XSLT转换。从源XML中获取nil值

我缺少的是零属性。我的意思是,如果源元素具有nil元素true 我想将其映射到目标XML。

<xsl:if 
test="string-length(soapenv:Envelope/soapenv:Body/b:getBLResponse/b:result/BResult:BLOut/Class:ID)=0"> 
    <xsl:attribute name="i:nil">true</xsl:attribute> 
</xsl:if> 

的,如果上述的特定节点的工作,但我希望把它作为通用模板, 不检查各个领域

也许它可以创建模板,将接收XML节点,比将验证节点是否具有零属性(如果是),则返回nil属性 否则无nil属性。

下面是例子

随着零输入:

<TEST> 
    <Child i:nil="true">asdf</Child> 
</TEST> 
Output: 

<TEST xmlns:i="whatever" > 
    <OutputChild i:nil="true">asdf</OutputChild > 
</TEST> 

Without nil: Input + Output the same 

<TEST> 
    <OutputChild >example</OutputChild > 
</TEST> 

为了解决这个问题,我写了模板,它接收映射节点和新的元素名称。在检查元素是否为空之后,模板返回nil属性

<xsl:template name="TransformNode" > 
     <xsl:param name="pCurrentNode"/> 
     <xsl:param name="elementName"/> 
     <xsl:element name = "{$elementName}"> 
      <xsl:if test="$pCurrentNode/@i:nil='true'"><xsl:attribute name="nil">true</xsl:attribute></xsl:if>  
      <xsl:value-of select="$pCurrentNode"/> 
     </xsl:element> 
    </xsl:template> 

我不知道,如果这是你在寻找什么(请:记得要经常包括输入和期望的输出XML),但在这里你有一个通用的模板,在应用任何额外的处理之前,可以清楚地看到空的节点和属性(如果你不需要属性检查,只需删除“或”之后的部分):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:i="whatever"> 
    <xsl:output method="xml" indent="yes"/> 
    <!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ --> 
    <xsl:template match="node()|@*"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
    </xsl:template> 
    <!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ --> 
    <xsl:template match="/*"> 
     <xsl:copy> 
      <xsl:variable name="nil"> 
       <xsl:apply-templates select="." mode="nil"/> 
      </xsl:variable> 
      <xsl:if test="$nil='true'"> 
       <xsl:attribute name="i:nil">true</xsl:attribute> 
      </xsl:if> 
      <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template> 
    <!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ --> 
    <xsl:template match="*" mode="nil"> 
     <xsl:choose> 
      <xsl:when test="string-length(.)=0 or @*[string-length(.)=0]"> 
       <xsl:value-of select="'true'"/> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:apply-templates select="*" mode="nil"/> 
      </xsl:otherwise> 
     </xsl:choose> 
    </xsl:template> 
</xsl:stylesheet> 

随着零: 输入:

<TEST> 
    <Child test="aaa" secondtest="">asdf</Child> 
</TEST> 

输出:

<TEST xmlns:i="whatever" i:nil="true"> 
    <Child test="aaa" secondtest="">asdf</Child> 
</TEST> 

不为零: 输入+输出(什么都不做):

<TEST> 
    <Child test="aaa" secondtest="bbb">asdf</Child> 
</TEST> 
+0

感谢您的帮助。但我需要一些不同的东西。我更新了答案 –