1

我知道我在这里遗漏了一些简单的东西,但我无法弄清楚。我还有其他更复杂的 XML 和 XSLT 正在工作,但由于某种原因,我无法实现这个特定的。我相信这是在序列化过程中生成的 XML 文件的结构。

我要做的是获取 XML 元素的值并将其显示在 HTML 中。除了与此问题相关的特定区域外,我已经删除了其他所有内容。

在代码中的“html”变量中,位置的值始终为空。

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);
4

1 回答 1

3

您的 XSL 模板匹配文档根节点,而不是文档元素(它们不是同一个东西)。尝试:

<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>

有关详细说明和其他用例,请参见此处。

于 2011-02-15T21:26:18.623 回答