我正在尝试反序列化一个看起来像这个
的xml文档<invoices>
<invoice>2848</invoice>
<invoice>2849</invoice>
<invoice>2850</invoice>
<invoice>2851</invoice>
<invoice>2852</invoice>
</invoices>
进入C#对象,但我无法让它工作。我正在使用DataContractSerializer
这就是我班上的样子:
[DataContract(Name = "invoices", Namespace = "")]
public class Invoices
{
[DataMember(Name = "invoice")]
public Invoice[] InvoiceIds { get; set; }
}
[DataContract(Name = "invoice", Namespace = "")]
public class Invoice
{
[DataMember(Name = "invoice")]
public string Id { get; set; }
}
当然这不起作用。我收到这个错误:
{"Error in line 1 position 24. Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''. "}
我无法控制Xml。
答案 0 :(得分:4)
尝试在此方案中使用[CollectionDataContract]
:
public class StackOverflow_10705733
{
[CollectionDataContract(Name = "invoices", ItemName = "invoice", Namespace = "")]
public class Invoices : List<int>
{
[DataMember(Name = "invoice")]
public int[] InvoiceIds { get; set; }
}
public static void Test()
{
DataContractSerializer dcs = new DataContractSerializer(typeof(Invoices));
string xml = @"<invoices>
<invoice>2848</invoice>
<invoice>2849</invoice>
<invoice>2850</invoice>
<invoice>2851</invoice>
<invoice>2852</invoice>
</invoices>";
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
Invoices value = dcs.ReadObject(ms) as Invoices;
Console.WriteLine(string.Join(",", value));
}
}