开发者

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. 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.ToSt开发者_开发百科ring();
Console.WriteLine(html);


Your XSL template matches the document root node, not the document element (they're not the same thing). 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜