2012-02-22 88 views
1

我有一個需要在xml文件上運行轉換。這將是非常基礎的,但在我有點迷路之前從未做過任何xslt工作。我已經有很多這樣的問題了,但是還沒有能夠解決這個問題?XSLT非常簡單的轉換需求

我所需要的是我的xml文件有一個模式引用,我需要將其更改爲不同的模式引用。

<?xml version="1.0" encoding="UTF-8"?> 
<Schedule xmlns="http://www.xxx.com/12022012/schedule/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.xxx.com/12022012/schedule/v2 ../Schema/Schema_v2.xsd"> 
    <Interface_Header> 
    </Interface_Header> 
... 
</Schedule> 

我只是想改變V2的V3到V3,並保持文件的其餘部分完好?這聽起來很簡單,但我似乎無法弄清楚這一點?我想一個簡單的XSLT這裏: -

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

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

但使用此我所有的值輸出沒有任何XML標記。

thanks in adv。

回答

0

用途:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:ns="new_namespace"> 
    <xsl:output method="xml" indent="yes"/> 

    <xsl:template match="@xsi:schemaLocation"> 
     <xsl:attribute name="xsi:schemaLocation"> 
      <xsl:text>new_schema_location</xsl:text> 
     </xsl:attribute> 
    </xsl:template> 

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

    <xsl:template match="*"> 
     <xsl:element name="{local-name()}" namespace="ns"> 
      <xsl:apply-templates select="node() | @*"/> 
     </xsl:element> 
    </xsl:template> 

</xsl:stylesheet> 

應用提供XML產生

<Schedule xsi:schemaLocation="new_schema_location" xmlns="ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <Interface_Header> 
    </Interface_Header> 
    ... 
</Schedule> 
+0

非常感謝。我在理解xmlns時遇到了一些困難:ns =「new_namespace」xmlns =「ns」piece,但我更改了的值,我。將不得不在我認爲的這個問題上做更多的閱讀。無論如何非常感謝。 – Purplemonkey 2012-02-22 17:12:05

+0

@Purplemonkey,歡迎光臨。 – 2012-02-22 17:14:46

0

當你並不需要新的架構位置有XSI的命名空間,那麼下面的工作:

<xsl:output indent="yes" method="xml"/> 

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

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

<xsl:template match="@*[local-name() = 'schemaLocation']"> 
    <xsl:attribute name="schemaLocation">newSchemaLocation</xsl:attribute> 
</xsl:template> 

當你確實需要再次使用xsi命名空間時,當然需要在模板,因此必須在樣式表頭中聲明,如下所示,其中local-name()函數被替換爲name()函數;前者包括命名空間,其中後者沒有:

<xsl:stylesheet 
    version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 

... 

    <xsl:template match="@*[name() = 'xsi:schemaLocation']"> 
     <xsl:attribute name="xsi:schemaLocation">newSchemaLocation</xsl:attribute> 
    </xsl:template> 

</xsl:stylesheet> 

注意,這兩個解決方案依賴於特定的模板路徑(@*[local-name()=...])具有更高的優先級比不太具體的(@*)。