在 .NET 中,如何将 UTF-16 XMLDocument 写入带有 BOM 的字符串
我正在动态构建 XmlDocument NET 与 xml 文档。 然后我用 Transform()< 进行转换XslCompiledTransform 的 /a> 方法。
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?
I am building an XmlDocument on the fly in .NET with an xml document. I then transform that with the Transform() method of an XslCompiledTransform.
The Transform() method threw an exception because an invalid character for the encoding was found in the stream. When I copy/paste the string with the help of the TextVisualizer in Visual Studio into Altova XmlSpy, it does not find an encoding problem.
I tried adding a UTF-16 header to the document to make it render as UTF-16 and calling Transform from the resulting text led to it complain about a BOM. Below is a simplified version of the code I used.
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);
Which I consequently am writing to a string like so:
StringBuilder sbXml = new StringBuilder();
using (XmlWriter wtr = XmlWriter.Create(sbXml))
{
xml.WriteTo(wtr);
// More code that calls sbXml.ToString());
}
What must I do to add the BOM or get XslCompiledTransform.Transform to not care about the bom?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要手动添加 xml 声明。
此代码会将 BOM 和声明添加到输出中。
如果需要 byte[] 形式的输出,可以使用 ms.ToArray() 的输出。 否则,您可以使用适当的 System.Text.Encoding 编码将 byte[] 转换为各种编码。
You don't need to manually add the xml declaration.
This code will add the BOM and the declaration to the output.
If you need the output as a byte[], you can use the output from ms.ToArray(). Otherwise you can use the appropriate System.Text.Encoding encoding to translate the byte[] into a variety of encodings.