我知道我在这里缺少一些简单的东西,但我无法理解。我有其他更复杂的XML和XSLT正在工作但由于某种原因我不能得到这个特定的。我相信这是在序列化过程中生成的XML文件的结构。
我要做的是获取XML元素的值并以HTML格式显示。除了与这个问题相关的具体领域之外,我已经取消了其他所有内容。
在代码中的“html”变量中,location的值始终为空。
XML
<WidgetBuilder>
<DefaultLocation>1234</DefaultLocation>
</WidgetBuilder>
XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" version="1.0" exclude-result-prefixes="msxsl">
<xsl:output method="html" indent="yes" />
<xsl:template match="/">
LOCATION: '<xsl:value-of select="DefaultLocation" />'
</xsl:template>
</xsl:stylesheet>
代码
string xml = File.ReadAllText(@"..\..\InitXml1.xml");
string xslt = File.ReadAllText(@"..\..\InitXslt1.xslt");
XPathDocument doc = new XPathDocument(new StringReader(xml));
XslCompiledTransform xslTransform = new XslCompiledTransform();
xslTransform.Load(XmlReader.Create(new StringReader(xslt)));
StringWriter sw = new StringWriter();
xslTransform.Transform(doc, null, sw);
string html = sw.ToString();
Console.WriteLine(html);
答案 0 :(得分:3)
您的XSL模板与document root node匹配,而不是文档元素(它们不是同一个东西)。尝试:
<xsl:value-of select="WidgetBuilder/DefaultLocation" />
编辑:此外,由于您使用的是默认命名空间,因此您必须从样式表中显示它:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:dc="schemas.datacontract.org/2004/07/YourFullClassName"
version="1.0" exclude-result-prefixes="msxsl">
<xsl:output method="html" indent="yes" />
<xsl:template match="/">
LOCATION: '<xsl:value-of select="dc:WidgetBuilder/dc:DefaultLocation" />'
</xsl:template>
</xsl:stylesheet>
有关详细说明和其他用例,请参阅here。