简体   繁体   English

使用value-of通过XSLT从XML元素获取值

[英]Getting the value from an XML element via XSLT using value-of

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. 我还有其他更复杂的XML和XSLT正在运行,但是由于某种原因,我无法继续使用这一特定功能。 I believe it's the structure of the XML file that's being generated during serialization. 我相信这是在序列化期间生成的XML文件的结构。

What I'm looking to do is get the value of an XML element and display it in HTML. 我想要做的是获取XML元素的值并将其显示为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. 在代码的“ html”变量中,location的值始终为空白。

XML XML

<WidgetBuilder>
  <DefaultLocation>1234</DefaultLocation>
</WidgetBuilder>

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

Your XSL template matches the document root node , not the document element (they're not the same thing). 您的XSL模板匹配文档根节点 ,而不是文档元素(它们不是同一对象)。 Try: 尝试:

<xsl:value-of select="WidgetBuilder/DefaultLocation" />

EDIT : Also, since you're using a default namespace, you'll have to make it visible from your stylesheet: 编辑 :另外,由于您使用的是默认名称空间,因此必须从样式表中使其可见:

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

See here for a detailed explanation and other use cases. 有关详细说明和其他用例,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM