使用 C# 的 XmlSerializer。
在反序列化给定文件夹中的所有 xml 文件的过程中,我看到 XmlException
"There is an error in XML document (0, 0)".
和 InnerException 是"There is no Unicode byte order mark. Cannot switch to Unicode".
目录中的所有 xml 都是“UTF-16”编码的。唯一的区别是,一些 xml 文件缺少在反序列化时我正在使用其对象的类中定义的元素。
例如,假设我的文件夹中有 3 种不同类型的 xml:
文件1.xml
<?xml version="1.0" encoding="utf-16"?>
<ns0:PaymentStatus xmlns:ns0="http://my.PaymentStatus">
</ns0:PaymentStatus>
文件2.xml
<?xml version="1.0" encoding="utf-16"?>
<ns0:PaymentStatus xmlns:ns0="http://my.PaymentStatus">
<PaymentStatus2 RowNum="1" FeedID="38" />
</ns0:PaymentStatus>
文件 3.xml
<?xml version="1.0" encoding="utf-16"?>
<ns0:PaymentStatus xmlns:ns0="http://my.PaymentStatus">
<PaymentStatus2 RowNum="1" FeedID="38" />
<PaymentStatus2 RowNum="2" FeedID="39" Amt="26.0000" />
</ns0:PaymentStatus>
我有一个类来表示上述 xml:
[XmlTypeAttribute(AnonymousType = true, Namespace = "http://my.PaymentStatus")]
[XmlRootAttribute("PaymentStatus", Namespace = "http://http://my.PaymentStatus", IsNullable = true)]
public class PaymentStatus
{
private PaymentStatus2[] PaymentStatus2Field;
[XmlElementAttribute("PaymentStatus2", Namespace = "")]
public PaymentStatus2[] PaymentStatus2 { get; set; }
public PaymentStatus()
{
PaymentStatus2Field = null;
}
}
[XmlTypeAttribute(AnonymousType = true)]
[XmlRootAttribute(Namespace = "", IsNullable = true)]
public class PaymentStatus2
{
private byte rowNumField;
private byte feedIDField;
private decimal AmtField;
public PaymentStatus2()
{
rowNumField = 0;
feedIDField = 0;
AmtField = 0.0M;
}
[XmlAttributeAttribute()]
public byte RowNum { get; set; }
[XmlAttributeAttribute()]
public byte FeedID { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal Amt { get; set; }
}
以下片段为我进行了反序列化:
foreach (string f in filePaths)
{
XmlSerializer xsw = new XmlSerializer(typeof(PaymentStatus));
FileStream fs = new FileStream(f, FileMode.Open);
PaymentStatus config = (PaymentStatus)xsw.Deserialize(new XmlTextReader(fs));
}
我错过了什么吗?它必须与编码格式有关,因为当我尝试用 UTF-8 手动替换 UTF-16 时,这似乎工作得很好。