2017-04-03 107 views
1

我有下面的類:XSLT變換字典<字符串,字符串>

public class HelloWorldDictionary 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public Dictionary<string, string> Items { get; set; } 
} 

而像這樣的XSLT:

<xsl:template match="/HelloWorldDictionary"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <br/> 
    <a> 
    Hi there <xsl:value-of select="FirstName" /> <xsl:value-of select="LastName" />! 
    </a> 
    <br/> 
    <br/> 
    <xsl:for-each select="Items/*"> 
    <xsl:value-of select="Key?" /> 
    <span> : </span> 
    <xsl:value-of select="Value?" /> 
    <br/> 
    </xsl:for-each> 
</html> 

正如可以預期,上述的換每個都不行...

生成的XML如下:

<HelloWorldDictionary xmlns="http://schemas.datacontract.org/2004/07/CommunicationTests.XsltEmail" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
<FirstName>Foo</FirstName> 
<Items xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> 
    <a:KeyValueOfstringstring> 
     <a:Key>Key1</a:Key> 
     <a:Value>12345678912</a:Value> 
    </a:KeyValueOfstringstring> 
    <a:KeyValueOfstringstring> 
     <a:Key>Key2</a:Key> 
     <a:Value>ABC1234</a:Value> 
    </a:KeyValueOfstringstring> 
    <a:KeyValueOfstringstring> 
     <a:Key>Key3</a:Key> 
     <a:Value>Test</a:Value> 
    </a:KeyValueOfstringstring> 
</Items> 
<LastName>Bar</LastName> 

什麼對我來說是正確的XSLT語法抓住從項目字典中的每個鍵值對?

+1

你到底該如何將xslt應用到你的班級? – Evk

+2

你的實際XML是什麼樣的?我假設你在應用樣式表之前序列化類。請將XML添加到問題中。 –

+0

對不起,我剛添加它。 – Matei

回答

2

隨着問題中的xml,命名空間是一個尷尬的位;你需要始終觀察命名空間。假設您有:

xmlns:dc="http://schemas.datacontract.org/2004/07/CommunicationTests.XsltEmail" 
xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" 

位於您的xslt頂部;那麼我們有(未經測試)類似:

<xsl:template match="/dc:HelloWorldDictionary"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <br/> 
    <a> 
    Hi there <xsl:value-of select="dc:FirstName" /> <xsl:value-of select="dc:LastName" />! 
    </a> 
    <br/> 
    <br/> 
    <xsl:for-each select="dc:Items/*"> 
    <xsl:value-of select="a:Key" /> 
    <span> : </span> 
    <xsl:value-of select="a:Value" /> 
    <br/> 
    </xsl:for-each> 
</html> 

但是,IMO你會更好堅持在大多數情況下,默認的(空)的命名空間;可悲的是,DataContractSerializer不同意...

+0

工作就像一個魅力。只需定義命名空間,使用別名和一切工作,謝謝! – Matei

相關問題