XSLT:如何使用XSLT将结构扁平化为XML 1

XSLT:如何使用XSLT将结构扁平化为XML 1

问题描述:

我正在尝试使用XSLT 1将层次结构/结构扁平化为XML,但没有成功。 - 即使找到好的链接...XSLT:如何使用XSLT将结构扁平化为XML 1

输入XML


<Address addressType="R"> 
<Structured xmlns="cds_dt"> 
    <Line1>15 Paradise</Line1> 
    <City>Toronto</City> 
    <CountrySubdivisionCode>-50</CountrySubdivisionCode> 
    <PostalZipCode> 
    <PostalCode>A1A1O1</PostalCode> 
    </PostalZipCode> 
</Structured> 
</Address> 

所需的输出XML


<Address addressType="R"> 
    <Formatted xmlns="cds_dt">15 Paradise, Toronto, A1A1O1</Formatted> 
</Address> 

我尝试这样做的.xsl但没有运气 - 错误文件


<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:x="cds"> 

<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*" /> 

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

<xsl:template match="*[ancestor::address]"> 
    <xsl:apply-templates/> 
</xsl:template> 

<xsl:template match="text()[ancestor::address::Structured]"> 
    <xsl:value-of select="concat('&#44;',.)"/> 
</xsl:template> 

</xsl:stylesheet> 

这种转变

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:x="cds_dt"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 

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

<xsl:template match="x:Structured"> 
    <xsl:element name="Formatted" namespace="cds_dt"> 
    <xsl:value-of select= 
    "concat(x:Line1, ', ', x:City, ', ', x:PostalZipCode/x:PostalCode)"/> 
    </xsl:element> 
</xsl:template> 
</xsl:stylesheet> 

时所提供的XML文档应用:

<Address addressType="R"> 
    <Structured xmlns="cds_dt"> 
     <Line1>15 Paradise</Line1> 
     <City>Toronto</City> 
     <CountrySubdivisionCode>-50</CountrySubdivisionCode> 
     <PostalZipCode> 
      <PostalCode>A1A1O1</PostalCode> 
     </PostalZipCode> 
    </Structured> 
</Address> 

产生想要的,正确的结果

<Address addressType="R"> 
    <Formatted xmlns="cds_dt">15 Paradise, Toronto, A1A1O1</Formatted> 
</Address> 

说明:覆盖identity rule +正确使用命名空间和<xsl:element>指令。

+0

非常感谢! – user610064 2012-03-05 16:41:36

+0

@ user610064:不客气。 – 2012-03-05 17:37:37

你的意思是类似的东西:

<Address addressType="R"> 
    <Formatted xmlns="cds_dt"> 
     <xsl:value-of select="concat(Line1, ', ', City, PostalZipCode/PostalCode)"/> 
    </Formatted> 
</Address> 

注:我已经缩短了参数的路径CONCAT()以提高可读性。因此,而不是Line1,它实际上应该是Address/Structured/Line1

+1

请不要发布未经测试的代码 - 它不会产生想要的结果。 – 2012-03-02 21:15:54