新的UTF8Encoding(false)仍在编写utf8 BOM

时间:2012-09-04 22:40:59

标签: c# xml utf-8 byte-order-mark

我在我的代码中关闭了BOM,它仍然在我的xml文档中打印它。我不明白。我已经查看了许多来源,但仍然没有,应该从

开始

我的代码确实这是一般的

XDocument xmlDoc = XDocument.Load(CompDir + File.Name);

AppendToFile(xmlDoc, aDataRow);

using (var writer = new XmlTextWriter
    (FilePrep.CompletedDirectory + File.Name, new UTF8Encoding(false))) 
    { 
    xmlDoc.Save(writer);
    writer.Close();
    }
break;

并且文件的附件看起来像这样

private void AppendToFile(XDocument xmlDoc, DataRow aDataRow)
{
    //String StrName = aDataRow.ItemArray.GetValue(5).ToString() + ' ' + aDataRow.ItemArray.GetValue(6).ToString();

    try
    {
        XElement foundEl = xmlDoc.Descendants("CreditScoreInfo").First();
        foundEl.Add(new XElement("CreditScore", aDataRow.ItemArray.GetValue(2)),
                    new XElement("CreditScoreDt", aDataRow.ItemArray.GetValue(1)));
                    //,new XElement("ScoredName", StrName)); 
    }
    catch
    {
       XElement persPolicy = xmlDoc.Descendants("PersPolicy").First();
                persPolicy.Add(new XElement("CreditScoreInfo",
                    new XElement("CreditScore", aDataRow.ItemArray.GetValue(2)),
                    new XElement("CreditScoreDt", aDataRow.ItemArray.GetValue(1))));
                    //,new XElement("ScoredName", StrName)));
    }
}

1 个答案:

答案 0 :(得分:2)

你能否尝试这种方式:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);

using (XmlWriter writer = XmlWriter.Create(FilePrep.CompletedDirectory + File.Name, settings))
{
    xmlDoc.Save(writer);
    writer.Close();
}