0

我正在使用 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());
        }

我必须怎么做才能添加 BOM 或让 XslCompiledTransform.Transform 不关心 bom?

4

1 回答 1

3

您不需要手动添加 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[] 转换为各种编码。

于 2009-07-31T00:14:00.003 回答