使用XSLT的XML到HTML转换不工作



我的Xml

<document>
<metadata>
<title>Sign in to my account</title>
</metadata>
<topic>
<conceptuldocument>
<legacybold> Hi hello world </legacybold>
</conceptuldocument>
</topic>
</document>

我只需要在元数据标签

下的标题我只需要<h1> sign in to my account</h1>

但是我把HTML输出为

<h1>sign in to my account</h1>Hi hello world

here my XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<xsl:choose>
<xsl:when  test="metadata">
<xsl:apply-templates select="metadata"/>
</xsl:when>
</xsl:choose>
</xsl:template>
<xsl:template match="metadata">
<h1>
<xsl:value-of select="title"/>
</h1>
</xsl:template>
</xsl:stylesheet>

c#:

using (StringWriter sw = new StringWriter())
{

transform.Transform(xmldocument.DocumentElement,null, sw);
string html = sw.ToString();
}

输出图像

xml图像Xslt文件映像

想知道是否有人可以帮助我指出我在这里错过了什么,非常新的XSLT刚刚一天。

最简单的修复方法是将条目模板更改为

<xsl:template match="/">
<xsl:apply-templates select="document/metadata"/>
</xsl:template>

注意,xsl:apply-templates周围的xsl:choose是浪费空间。如果元素不存在,xsl:apply-templates将不执行任何操作。

最新更新