使用 value-of 通过 XSLT 从 XML 元素获取值
我知道我在这里错过了一些简单的东西,但我无法弄清楚。我还有其他更复杂的 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);
I know I'm missing something simple here, yet I can't figure it out. I have other, more complex, XML and XSLT that are working but for some reason I can't get this specific one going. I believe it's the structure of the XML file that's being generated during serialization.
What I'm looking to do is get the value of an XML element and display it in HTML. I've taken everything else away except the specific areas related to this issue.
In the "html" variable in the code, the value for location is always blank.
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>
Code
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 XSL 模板匹配 文档根节点,而不是文档元素(它们'它们不是同一件事)。尝试:
编辑:此外,由于您使用的是默认名称空间,因此您必须使其在样式表中可见:
请参阅此处了解详细说明和其他用例。
Your XSL template matches the document root node, not the document element (they're not the same thing). Try:
EDIT: Also, since you're using a default namespace, you'll have to make it visible from your stylesheet:
See here for a detailed explanation and other use cases.