Question

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");
Was it helpful?

Solution

If all you want is to avoid the creation of a BOM, that's easy - just create a UTF8Encoding which doesn't use one and an XmlWriterSettings with that encoding:

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);
}

Or just create an appropriate TextWriter:

var path = Path.Combine(pathDesktop, "\\22CRE002.XPO");
using (var writer = new StreamWriter(path, false, new UTF8Encoding(false)))
{
    doc.Save(writer);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top