我有byte[] byteArray格式的xml数据,其中可能包含也可能不包含物料清单。在C#中有什么标准的方法来删除物料清单吗?如果不是,那么处理所有情况(包括所有类型的编码)的最佳方法是什么?
实际上,我正在修复代码中的错误,我不想更改太多代码。所以如果有人能给我删除BOM的代码就更好了。
我知道我可以找出60,这是'<‘的ASCII值,然后忽略之前的字节,但我不想这样做。
发布于 2013-03-18 19:53:12
所有的BOM解析器都会自动为您处理C#。我推荐使用XDocument --在我看来,它提供了最干净的XML数据抽象。
以XDocument为例:
using (var stream = new memoryStream(bytes))
{
var document = XDocument.Load(stream);
...
}一旦你有了一个XDocument,你就可以用它来省略没有XDocument的字节:
using (var stream = new MemoryStream())
using (var writer = XmlWriter.Create(stream))
{
writer.Settings.Encoding = new UTF8Encoding(false);
document.WriteTo(writer);
var bytesWithoutBOM = stream.ToArray();
}发布于 2013-05-01 17:43:54
您可以这样做,以便在从流读取时跳过BOM字节。您需要扩展Bom.cs以包括进一步的编码,但是afaik UTF是使用BOM的唯一编码...然而,关于这一点,可能(很可能)是错误的。
我从here得到了编码类型的信息
using (var stream = File.OpenRead("path_to_file"))
{
stream.Position = Bom.GetCursor(stream);
}
public static class Bom
{
public static int GetCursor(Stream stream)
{
// UTF-32, big-endian
if (IsMatch(stream, new byte[] {0x00, 0x00, 0xFE, 0xFF}))
return 4;
// UTF-32, little-endian
if (IsMatch(stream, new byte[] { 0xFF, 0xFE, 0x00, 0x00 }))
return 4;
// UTF-16, big-endian
if (IsMatch(stream, new byte[] { 0xFE, 0xFF }))
return 2;
// UTF-16, little-endian
if (IsMatch(stream, new byte[] { 0xFF, 0xFE }))
return 2;
// UTF-8
if (IsMatch(stream, new byte[] { 0xEF, 0xBB, 0xBF }))
return 3;
return 0;
}
private static bool IsMatch(Stream stream, byte[] match)
{
stream.Position = 0;
var buffer = new byte[match.Length];
stream.Read(buffer, 0, buffer.Length);
return !buffer.Where((t, i) => t != match[i]).Any();
}
}发布于 2019-02-17 09:52:45
您不必担心BOM。
如果出于某种原因,您需要使用XmlDocument对象,也许下面的代码可以帮助您:
byte[] file_content = {wherever you get it};
XmlDocument xml = new XmlDocument();
xml.Load(new MemoryStream(file_content));当我使用Google Api和Encoding.UTF8.GetString(file_content)试图从gmail帐户下载一个xml附件,文件有BOM和Encoding.UTF8.GetString不能“正常”工作时,它对我起作用了。
https://stackoverflow.com/questions/15476113
复制相似问题