我有以下课程:
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>
正如您所料,上述for-each将无效......
生成的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>
从Items词典中获取每个键值对的正确XSLT语法是什么?
答案 0 :(得分: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
不同意......