2009-11-13 123 views
35

我有一些XML,我試圖使用XSLT轉換爲HTML,但我無法讓它爲我的生活工作。有人能告訴我我做錯了什麼嗎?XSLT使用命名空間轉換XML

XML

<ArrayOfBrokerage xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.test.com/"> 
    <Brokerage> 
     <BrokerageID>91</BrokerageID> 
     <LastYodleeUpdate>0001-01-01T00:00:00</LastYodleeUpdate> 
     <Name>E*TRADE</Name> 
     <Validation i:nil="true" /> 
     <Username>PersonalTradingTesting</Username> 
    </Brokerage> 
</ArrayOfBrokerage> 

XSLT

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

    <xsl:output method="html" indent="no"/> 

    <xsl:template match="/ArrayOfBrokerage"> 
     <xsl:for-each select="Brokerage"> 
      Test 
     </xsl:for-each> 
    </xsl:template> 

</xsl:stylesheet> 

回答

49

您需要在xslt中爲正在轉換的元素提供名稱空間前綴。出於某種原因(至少在Java JAXP解析器中),不能簡單地聲明默認名稱空間。這對我有用:

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

    <xsl:output method="html" indent="no"/> 

    <xsl:template match="/t:ArrayOfBrokerage"> 
     <xsl:for-each select="t:Brokerage"> 
      Test 
     </xsl:for-each> 
    </xsl:template> 

</xsl:stylesheet> 

這將捕獲您的XML文檔中命名空間的所有內容。

+0

這也適用於我的測試(在Visual Studio 2008中運行XSLT調試) – Murph 2009-11-13 18:19:37

+0

這確實有用。我曾嘗試過使用exclude-result-prefixes =「t」的組合,因爲我認爲它可以讓我在每個節點之前不必粘貼t :.有沒有辦法避免這樣做? – Chris 2009-11-13 18:21:10

+2

我不認爲有。 – 2009-11-13 18:23:38

-2

你如何執行轉換?也許你忘了將XSLT樣式錶鏈接到XML文檔使用:

<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?> 

在XML文檔的開頭。 More explanation here

+0

我不確定這是什麼意思。實際上,我並未對XML文件進行轉換,而是使用DataContractSerializer序列化業務對象,並在對象的DataContract中指定命名空間。 – Chris 2009-11-13 18:09:17