2016-11-21 76 views
1

我有一个XML,其中几个简单标签出现在嵌套标签后面。我试图找出一种方法,如果有可能将所有简单标签放在嵌套标签上方。 例XSLT将复杂标签上的简单标签带入XML中

<Country> 
<row> 
    <CountryId>1</CountryId> 
    <State> 
     <StateId>2</StateId> 
     <StateName>Karnataka</StateName> 
    </State> 
    <CountryName>India</CountryName> 
</row> 
<row> 
    <CountryId>3</CountryId> 
    <State> 
     <StateId>4</StateId> 
     <StateName>Sydney</StateName> 
    </State> 
    <CountryName>Australia</CountryName> 
</row> 

,预计

转换的XML是:

<Country> 
<row> 
    <CountryId>1</CountryId> 
    <CountryName>India</CountryName> 
    <State> 
     <StateId>2</StateId> 
     <StateName>Karnataka</StateName> 
    </State> 
</row> 
<row> 
    <CountryId>3</CountryId> 
    <CountryName>Australia</CountryName> 
    <State> 
     <StateId>4</StateId> 
     <StateName>Sydney</StateName> 
    </State> 
</row> 

这个XML可以是任何通用的XML有n个级别,所以我想硬编码的任何XSLT中的标签。 XSLT应该能够处理一个巨大的XML,将所有简单的标签放在嵌套标签上。使用XSLT做这件事是可取的吗?还有哪些其他选择?

回答

2

我只想做:

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="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"> 
      <xsl:sort select="boolean(*)" data-type="text" order="ascending"/> 
     </xsl:apply-templates> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 
+0

谢谢michael.hor257k,这个解决方案非常简单,像一个魅力。 ... – Supriya

2

如果你没有混合内容(即元素既有文本也有元素内容),你可以简单地为那些具有元素内容的元素编写一个模板match="*[*]",它首先处理没有子元素的子元素元素。使用XSLT 2.0可以实现与

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> 

    <xsl:output indent="yes"/> 

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

    <xsl:template match="*[*]"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*, *[not(*)], *[*]"/> 
     </xsl:copy> 
    </xsl:template> 

</xsl:transform> 

在线在http://xsltransform.net/pPJ8LVo

如果你只有一个XSLT 1.0处理器,那么你必须打破了<xsl:apply-templates select="@*, *[not(*)], *[*]"/>

<xsl:apply-templates select="@* | *[not(*)]"/> 
<xsl:apply-templates select="*[*]"/> 
+0

感谢马丁Honnen ....就像一个魅力...我试着用XSLT 1.0 .... – Supriya