我正在使用.NET framework 3.5中提供的XslCompiledTransform类将我的XML文件转换为另一个XML文件
这是我的代码。
private static void transformUtil(string sXmlPath, string sXslPath, string outputFileName)
{
try
{
XPathDocument myXPathDoc = new XPathDocument(sXmlPath);
XslCompiledTransform myXslTrans = new XslCompiledTransform();
//load the Xsl
myXslTrans.Load(sXslPath);
//create the output stream
XmlTextWriter myWriter = new XmlTextWriter(outputFileName, null);
//do the actual transform of Xml
myXslTrans.Transform(myXPathDoc, null, myWriter);
myWriter.Close();
}
catch (Exception e)
{
EventLogger eventLog;
eventLog = new EventLogger("transformUtil", e.ToString());
}
}
}
代码有效,但输出文件在标题中没有XML声明。
**<?xml version="1.0" encoding="utf-8"?>**
我无法理解这一点。当我使用相同的XSL文件来转换XML时,使用像notepad ++或visual studio这样的工具,转换在头文件中包含XML声明。那么XslCompiledTransform是否负责截断此声明?我很困惑。
其他人遇到类似问题?
我的XSL文件标题如下所示。
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
答案 0 :(得分:1)
使用的XML编写器没有任何与之关联的设置。
更改强>
//create the output stream
XmlTextWriter myWriter = new XmlTextWriter(outputFileName, null);
以强>
XmlWriterSettings settings =
new XmlWriterSettings
{
OmitXmlDeclaration = false
};
XmlWriter myWriter = XmlWriter.Create(outputFileName, settings);
或者,您可以更少地设置转换:
private static void transformUtil(string sXmlPath, string sXslPath,
string outputFileName)
{
try
{
XslCompiledTransform xsl = new XslCompiledTransform();
// Load the XSL
xsl.Load(sXslPath);
// Transform the XML document
xsl.Transform(sXmlPath, outputFileName);
}
catch (Exception e)
{
// Handle exception
}
}
这也应该遵循XSLT文件本身的xsl:output指令,特别是omit-xml-declaration
属性,如果未指定,默认值为“no”。