处理嵌套节点(名称不同,内容相同)的最优方法



我必须转换如下所示的xml消息。每个节点的源内容实际上是相同的,只是具有不同的节点名称(parentiitem、childitem、subchild)。

我继承了一个XSLT,它通过硬编码每种情况来解决这个问题,很少使用模板,这有大量重复的XSLT。

我想知道我有什么选项来优化XSLT以减少XSLT的重复。

我试图为一个通用的"节点";然后尝试使用call-template;然而,我不知道如何在泛型

内嵌套对象。任何帮助都很感激,谢谢。

<item>
<itemdetail>
<parentitem>
<item>001</item>
<code1>1</code1>
<code2>2</code2>
<itemattribute>
<item_desc>ParentItem</item_desc>
</itemattribute>
</parentitem>
<childitem>
<item>002</item>
<code1>2</code1>
<code2>2</code2>
<itemattribute>
<item_desc>ChildItemLevel1</item_desc>
</itemattribute>
</childitem>
<subchildren>
<subchild>
<item>003</item>
<code1>2</code1>
<code2>1</code2>
<itemattribute>
<item_desc>SubChild003</item_desc>
</itemattribute>
</subchild>
<subchild>
<item>004</item>
<code1>2</code1>
<code2>1</code2>
<itemattribute>
<item_desc>SubChild004</item_desc>
</itemattribute>
</subchild>
</subchildren>
</itemdetail>
</item>

消息有几个变体所需的转换需要与下面类似。

  • 父级和子级只有0或1个实例
  • 嵌套在父
  • 子节点(ren)嵌套在子节点
  • 下。
tbody> <<tr>
Caseparentitem NodeChildItem PresentSubChildren Present
案例1YYY
案例2YNN
情况3YYN
案例4NYN
案例5NYY
案例6NNY

这样的东西适合你吗?我相信它覆盖情况下甚至比6阐述。

XSLT 1.0

<xsl:stylesheet version="1.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="*"/>
<xsl:template match="itemdetail">
<Products>
<xsl:apply-templates select="parentitem"/>
<xsl:apply-templates select="childitem[not(../parentitem)]"/>
<xsl:apply-templates select="subchildren[not(../parentitem | ../childitem)]"/>
</Products>
</xsl:template>
<xsl:template match="parentitem">
<Product type="parentitem">
<xsl:copy-of select="*"/>
<xsl:apply-templates select="../childitem"/>
<xsl:apply-templates select="../subchildren[not(../childitem)]"/>
</Product>
</xsl:template>
<xsl:template match="childitem">
<Product type="childitem">
<xsl:copy-of select="*"/>
<xsl:apply-templates select="../subchildren"/>
</Product>
</xsl:template>
<xsl:template match="subchild">
<Product type="subchild">
<xsl:copy-of select="*"/>
</Product>
</xsl:template>
</xsl:stylesheet>