我正在使用 XSLT/Xalan 将一个 XML 文件转换为另一个。这样做时,我发现当我创建我的 XSLT 样式表时,我正在硬编码我想要生成的目标文件的节点。这看起来很奇怪。
反正有没有使用 XSD 以编程方式生成目标文件?我想基本上使用我拥有的 XSD 创建文件的骨架,然后针对源文件运行我的样式表。然后,我可以将我从那里找到的值插入生成文件中的适当位置。
有没有办法做到这一点?或者 XQuery 是否可能提供类似的功能?
听起来您在问如何序列化 DataSet 并使用 XSLT 对其进行转换。如果是这样,您可以这样做:
将数据集序列化为 XML
DataTable table = new DataTable();
System.IO.StringWriter writer = new System.IO.StringWriter();
//notice that we're ignoring the schema so we get clean XML back
//you can change the write mode as needed to get your result
table.WriteXml(writer, XmlWriteMode.IgnoreSchema, false);
string dataTableXml = writer.ToString();
至于以可读格式显示它,我建议将 XML 传递给 XSL 转换器,然后您可以使用它来解析 XML 并根据需要操作输出。
将 XSLT 转换应用于数据集
http://msdn.microsoft.com/en-us/library/8fd7xytc%28v=vs.71%29.aspx#Y289
这是我创建的一个简单示例,用于解释如何使用 XSL 转换器。我还没有测试它,但它应该非常接近:
DataSet ds = new DataSet();
StringBuilder sbXslOutput = new StringBuilder();
using (XmlWriter xslWriter = XmlWriter.Create(sbXslOutput))
{
XslCompiledTransform transformer = new XslCompiledTransform();
transformer.Load("transformer.xsl");
XsltArgumentList args = new XsltArgumentList();
transformer.Transform(new XmlDataDocument(ds), args, xslWriter);
}
string dataSetHtml = sbXslOutput.ToString();
使用 XSLT 将 XML 格式化为 HTML
下面是使用 XSLT 将 XML 转换为 HTML 表的示例。它应该很容易采用,因此您可以将它与您的序列化数据集一起使用。
假设这是您的 DataSet,序列化为 XML:
<RecentMatter>
<UserLogin>PSLTP6\RJK</UserLogin>
<MatterNumber>99999-2302</MatterNumber>
<ClientName>Test Matters</ClientName>
<MatterName>DP Test Matter</MatterName>
<ClientCode>99999</ClientCode>
<OfficeCode/>
<OfficeName/>
<Billable>true</Billable>
<ReferenceId/>
<LastUsed>2011-08-23T23:40:24.13+01:00</LastUsed>
</RecentMatter>
<RecentMatter>
<UserLogin>PSLTP6\RJK</UserLogin>
<MatterNumber>999991.0002</MatterNumber>
<ClientName>Lathe 1</ClientName>
<MatterName>LW Test 2</MatterName>
<ClientCode/>
<OfficeCode/>
<OfficeName/>
<Billable>true</Billable>
<ReferenceId/>
<LastUsed>2011-07-12T16:57:27.173+01:00</LastUsed>
</RecentMatter>
<RecentMatter>
<UserLogin>PSLTP6\RJK</UserLogin>
<MatterNumber>999991-0001</MatterNumber>
<ClientName>Lathe 1</ClientName>
<MatterName>LW Test 1</MatterName>
<ClientCode/>
<OfficeCode/>
<OfficeName/>
<Billable>false</Billable>
<ReferenceId/>
<LastUsed>2011-07-12T01:59:06.887+01:00</LastUsed>
</RecentMatter>
</NewDataSet>
这是一个将 DataSet 转换为 HTML 的 XSLT 脚本:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<table border="1">
<tr>
<th>User Login</th>
<th>Matter Number</th>
...
</tr>
<xsl:for-each select="NewDataSet/RecentMatter">
<tr>
<td>
<xsl:value-of select="UserLogin"/>
</td>
<td>
<xsl:value-of select="MatterNumber"/>
</td>
...
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
使用 XSLT 2.0,您可以利用模式信息(源文档和目标文档)使系统能够检查样式表的正确性,如果您尝试访问输入或生成对架构。但我不知道有任何工具使用模式来自动化创建样式表的过程。可能是某些 XSLT 编辑工具 (IDE) 使用模式信息来帮助进行语法指导的编辑。