我正在使用xml文档在.NET中动态构建一个XmlDocument。然后,我使用XslCompiledTransform的Transform()方法对其进行转换。
Transform()方法引发异常,因为在流中发现编码的无效字符。当我在Visual Studio中的TextVisualizer的帮助下将字符串复制/粘贴到Altova XmlSpy中时,它没有发现编码问题。
我尝试向文档添加一个UTF-16头文件,使其呈现为UTF-16格式,并从生成的文本调用Transform,结果导致它抱怨BOM。下面是我使用的代码的简化版本。
XmlDocument document = new XmlDocument();
XmlDeclaration decl = document.CreateXmlDeclaration("1.0", "UTF-16", null);
document.AppendChild(decl);
XmlNode root = document.CreateNode(XmlNodeType.Element, "RootNode", "");
XmlNode nodeOne = document.CreateNode(XmlNodeType.Element, "FirstChild", null);
XmlNode nodeTwp = doc.CreateNode(XmlNodeType.Element, "Second Child", null);
root.AppendChild(nodeOne);
root.AppendChild(nodeTwo);
document.AppendChild(root);因此我将其写入如下所示的字符串:
StringBuilder sbXml = new StringBuilder();
using (XmlWriter wtr = XmlWriter.Create(sbXml))
{
xml.WriteTo(wtr);
// More code that calls sbXml.ToString());
}我必须做什么才能添加物料清单或让XslCompiledTransform.Transform不关心物料清单?
发布于 2009-07-31 00:14:00
您不需要手动添加xml声明。
此代码会将BOM和声明添加到输出中。
XmlDocument document = new XmlDocument();
// XmlDeclaration decl = document.CreateXmlDeclaration("1.0", "UTF-16", null);
// document.AppendChild(decl);
XmlNode root = document.CreateNode(XmlNodeType.Element, "RootNode", "");
XmlNode nodeOne = document.CreateNode(XmlNodeType.Element, "FirstChild", null);
XmlNode nodeTwo = document.CreateNode(XmlNodeType.Element, "SecondChild", null);
root.AppendChild(nodeOne);
root.AppendChild(nodeTwo);
document.AppendChild(root);
using(MemoryStream ms = new MemoryStream())
{
StreamWriter sw = new StreamWriter(ms, Encoding.Unicode);
document.Save(sw);
Console.Write(System.Text.Encoding.Unicode.GetString(ms.ToArray()));
}如果需要将输出作为byte[],可以使用ms.ToArray()的输出。否则,您可以使用适当的System.Text.Encoding编码将byte[]转换为各种编码。
https://stackoverflow.com/questions/1209703
复制相似问题