我正在尝试通过代码创建XML文件。该文件正在成功创建,但该文件所需的系统只读取UTF-8。该文件未成功加载,因为它们是一些隐藏的字符。
此隐藏字符会生成错误。我在想我需要设置一个假的但不知道如何。您可以在下面找到用于生成我的文件的代码。
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);
基本上我使用的是C#和XElement类,它通过在参数中传递名称标签和数据来创建XML。
最后,我将所有XElements存储在XDocument中,如下所示,以创建XML样式文档并将文件另存为.XPO
XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
xdoc.Save(pathDesktop + "\\22CRE002.XPO");
答案 0 :(得分:4)
如果你想要的只是避免创建一个BOM,那很容易 - 只需创建一个不使用一个的UTF8Encoding
和一个XmlWriterSettings
的编码:
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);
}