如何创建一个xsl模板,可以将元素的名称和值写为KVP,然后递归处理所有兄弟节点和子节点

时间:2015-10-02 20:49:44

标签: xml xslt

所以我需要创建一个变换,它可以使用制表符分隔符以KVP格式返回元素的名称及其值。诀窍是,我需要节点本身及其列表中返回的所有子节点。订购并不重要

Xml示例:

<Holding id="Holding_1">
  <HoldingTypeCode tc="2">PolicyType</HoldingTypeCode>
  <HoldingStatus tc="3">ProposedStatus</HoldingStatus>
  <Policy id="Policy_1">
    <PolNumber>0123456789</PolNumber>
    <LineOfBusiness tc="1">LifeBusiness</LineOfBusiness>
  </Policy>
</Holding>

在我的XSLT中,我有这个调用模板:

<xsl:call-template name="List_Siblings_And_Children_Recursive">
  <xsl:with-param name="Parent" select="//Holding"></xsl:with-param>
</xsl:call-template>

这是模板本身:

<xsl:template name="List_Siblings_And_Children_Recursive">
<xsl:param name="Parent"></xsl:param>

<!-- TAB & CRLF CHAR-->
<xsl:variable name="tab">
  <xsl:text>&#x9;</xsl:text>
</xsl:variable>
<xsl:variable name="CRLF">
  <xsl:text>&#10;&#13;</xsl:text>
</xsl:variable>

<!-- LIST EACH ELEMENT IN THE LIST OF SIBLINGS, RECURSIVELY CHECK FOR ANY CHILDREN -->
<xsl:for-each select="$Parent/*">
  <xsl:value-of select="local-name()"/>
  <xsl:value-of select="$tab"/>
  <xsl:value-of select="."/>
  <xsl:value-of select="$CRLF"/>
  <xsl:call-template name="List_Siblings_And_Children_Recursive">
    <xsl:with-param name="Parent" select="./*"></xsl:with-param>
  </xsl:call-template>
</xsl:for-each>

我的模板有什么问题?我正在寻找的输出应该如下:

HoldingTypeCode    PolicyType
HoldingStatus      ProposedStatus
Policy
PolNumber     0123456789
LineOfBusiness     LifeBusiness

1 个答案:

答案 0 :(得分:0)

  

我的模板有什么问题?

AFAICT,主要问题在于递归调用:

<xsl:call-template name="List_Siblings_And_Children_Recursive">
  <xsl:with-param name="Parent" select="./*"></xsl:with-param>
</xsl:call-template>

我认为应该是:

<xsl:call-template name="List_Siblings_And_Children_Recursive">
  <xsl:with-param name="Parent" select="."></xsl:with-param>
</xsl:call-template>

请注意,XSLT的本地processing model是递归的,因此您可以通过利用它来简化这一过程 - 比如说:

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

<xsl:template match="*">
    <xsl:value-of select="name()"/>
    <xsl:text>&#x9;</xsl:text>
    <xsl:value-of select="text()"/>
    <xsl:text>&#10;&#13;</xsl:text>
    <xsl:apply-templates select="*"/>
</xsl:template>

</xsl:stylesheet>

还要注意:

之间的区别
<xsl:value-of select="."/>

<xsl:value-of select="text()"/>