首先,您的源 xml 中应该有一个根元素,所以我将其更改如下:
源 XML
<rows>
<row>
<column1>
ABC
</column1>
<column2>
ABC
</column2>
</row>
<row>
<column1>
123
</column1>
<column2>
123
</column2>
</row>
<row>
<column1>
234
</column1>
<column2>
234
</column2>
</row>
</rows>
必需的 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="rows">
<xsl:for-each select="row">
<xsl:if test="position() = 1">
<div class="firstrow">
<xsl:call-template name="PrintColumnValues"></xsl:call-template>
</div>
</xsl:if>
<div class="tabpanel">
<xsl:call-template name="PrintColumnValues"></xsl:call-template>
</div>
</xsl:for-each>
</xsl:template>
<xsl:template name="PrintColumnValues">
<xsl:value-of select="column1"/>
<xsl:value-of select="column2"/>
</xsl:template>
</xsl:stylesheet>
使用此 xslt 转换源 xml 后,您将获得所需的 html 输出。
注意:作为帮助,我添加了一些可用于 xslt 转换的代码。
public static string TransformContentXmlwithXslt(XmlDocument xmlDocument, string xsltFileName)
{
//Load the XML data document
MemoryStream contentStream = new MemoryStream();
xmlDocument.Save(contentStream);
contentStream.Position = 0;
XPathDocument mergedXPathDocument = new XPathDocument(contentStream);
XsltSettings xsltJsSetting = new XsltSettings();
xsltJsSetting.EnableScript = true;
//Load the XSLT file
string xsltFilePath = xsltFileName;
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xsltFilePath, xsltJsSetting, new XmlUrlResolver());
//Do the transformation
MemoryStream transformedContentMemoryStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(transformedContentMemoryStream, Encoding.UTF8);
StreamReader streamReader = new StreamReader(transformedContentMemoryStream);
xslt.Transform(mergedXPathDocument, writer);
transformedContentMemoryStream.Position = 0;
string transformedHtml = streamReader.ReadToEnd();
//// Close the connections
streamReader.Close();
transformedContentMemoryStream.Close();
return transformedHtml;
}
在这里,xsltFileName
应该包含完整的文件路径。
您可以通过调用此方法获得转换后的输出。