【问题标题】:Generating XML in UTF-8 without BOM在没有 BOM 的情况下以 UTF-8 生成 XML
【发布时间】:2019-03-07 10:52:12
【问题描述】:

我正在尝试仅使用“UTF-8”编码生成 XML 消息:

Dim doc As System.Xml.XmlDataDocument = New System.Xml.XmlDataDocument(ds)
Dim n1 As System.Xml.XmlNode = doc.FirstChild



Dim doc2 As System.Xml.XmlDocument = New System.Xml.XmlDocument
doc2.LoadXml(n1.FirstChild.OuterXml)



doc2.InsertBefore(doc2.CreateXmlDeclaration("1.0", "utf-8", "yes"), doc2.FirstChild)
doc2.Save(outFile)

但是,每次生成文件时,编码都会列为“UTF-8 签名”。我尝试使用以下内容从消息中删除前三个字符:

def xmlbytes = outFile.toString().getBytes().flatten()
xmlbytes.remove(0)
xmlbytes.remove(0)
xmlbytes.remove(0) 

也失败了。

是否有更有效的方法来确保编码仅保留为“UTF-8”?

我没有使用 xDocument,因此我无法从其他线程应用解决方案。

【问题讨论】:

标签: xml visual-studio-2010 vb.net-2010


【解决方案1】:

我认为XDocument 的使用会让您感到困惑——possible duplicate 中详述的解决方案仍应适用。但要清楚,

代替

doc2.Save(outFile)

试试

using (var writer = new XmlTextWriter(outFile, new UTF8Encoding(false)))
{
    doc2.Save(writer);
}

【讨论】:

    猜你喜欢
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多