繁体   English   中英

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

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

我知道我在这里缺少一些简单的东西,但我无法弄清楚。 我还有其他更复杂的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);

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

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

暂无
暂无

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

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