2012-03-02 109 views
2

我正在嘗試使用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> 

回答

3

這種轉變

<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

0

你的意思是類似的東西:

<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