Pergunta

Como remover o BOM de um arquivo XML que está sendo criado?

Eu tentei usar o novo método UTF8Encoding (FALSE), mas não funciona. Aqui está o código que tenho:

XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter(filename, new UTF8Encoding(false));
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("items");
xmlWriter.Close();
xmlDoc.Load(filename);
XmlNode root = xmlDoc.DocumentElement;
XmlElement item = xmlDoc.CreateElement("item");
root.AppendChild(item);
XmlElement itemCategory = xmlDoc.CreateElement("category");
XmlText itemCategoryText = xmlDoc.CreateTextNode("test");
item.AppendChild(itemCategory);
itemCategory.AppendChild(itemCategoryText);
xmlDoc.Save(filename);
Foi útil?

Solução

Você está salvando o arquivo duas vezes - uma vez com XmlTextWriter e uma vez com xmlDoc.Save. Salvando do XmlTextWriter não é adicionando um nascido - economizando com xmlDoc.Save é.

Apenas salve para um TextWriter Em vez disso, para que você possa especificar a codificação novamente:

using (TextWriter writer = new StreamWriter(filename, false,
                                            new UTF8Encoding(false))
{
    xmlDoc.Save(writer);
}

Outras dicas

Em vez disso, eu escrevia o XML em uma string (construtor) e, em seguida, escrevia essa string para arquivo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top