0

I am trying to create an XML file through code. The file is being created successfully but my system needed for the file only reads UTF-8. The file is not being loaded successfully as their are some hidden characters.

This hidden characters are generated an error. I am thinking that I need to set the bom a false but dont have any idea how. below you can find my code used for generating my file.

 XElement xElement = new XElement("Transaction", 
                new XElement("TransactionNumber", counter),
                new XElement("TransactionReferenceNumber", "CRE" + payItem.ID),
                new XElement("TransactionDate", DateTime.Today.Date.ToString("yyyy-MM-dd")),
                new XElement("BankID", "99"),
                new XElement("SourceAccountNumber", currentAccount.AccountNumber),
                new XElement("BeneficiaryName", RemoveSpecialCharacters(payItem.WIRE_BENEF_NAME)),
                new XElement("PaymentDetails1", details),
                new XElement(checkForAccountDetails(payItem.WIRE_BENEF_BANK_IBAN), getIBANorNumber(payItem)),
                new XElement("POCurrency", payItem.Currency),
                new XElement("POAmount", payItem.NET_DEPOSIT),
                new XElement("BeneficiaryType", "FINANCIAL"),
                new XElement("Residence", "NON-RESIDENT"),
                new XElement("IncurredChargesBy", "SHARED"),
                new XElement("ExchangeControlClassification", "OTHER PAYMENTS"),
                new XElement("TypeofPayment", "T3"),
                new XElement("SectorCode", "COS"),
                new XElement("Priority", getPaymentPriority(payItem.Currency)),
                new XElement("SwiftAddress", payItem.WIRE_BENEF_BANK_SWIFT_CDE),
                new XElement("BankCountry", currentBank.Country.ToUpper())
            );
            xDetail.Add(xElement);

Basically I am using C# and the XElement class, which creates XML by passing the name tag and data in parameters.

Finally I am storing all the XElements in an XDocument as shown below to created an XML style document and saving the file as .XPO

XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
xdoc.Save(pathDesktop + "\\22CRE002.XPO");
4

1 回答 1

4

如果您只想避免创建 BOM,那很容易 - 只需创建一个UTF8Encoding不使用 one 和 anXmlWriterSettings的编码:

var path = Path.Combine(pathDesktop, "\\22CRE002.XPO");
var settings = new XmlWriterSettings { 
    Encoding = new UTF8Encoding(false),
    Indent = true
};
using (var writer = XmlWriter.Create(path, settings))
{
    doc.Save(writer);
}

或者只是创建一个适当的TextWriter

var path = Path.Combine(pathDesktop, "\\22CRE002.XPO");
using (var writer = new StreamWriter(path, false, new UTF8Encoding(false)))
{
    doc.Save(writer);
}
于 2013-09-23T14:47:16.357 回答