我正在尝试将XML doc(invoiceList)转换为对象。理想情况下,我想将其转换为对象的集合(“发票”)。
下面是XML的片段。我还在INVOICE对象中添加了一个片段。最后是我尝试反序列化的尝试。我收到的错误消息是如此无用,以至于我不知道从哪里开始。
<?xml version="1.0" encoding="utf-8"?>
<invoiceListResponse>
<invoiceList>
<invoiceListItem>
<invoiceUid>39165890</invoiceUid>
<lastUpdatedUid>AAAAADrKwis=</lastUpdatedUid>
<ccy>JPY</ccy>
<autoPopulateFXRate>false</autoPopulateFXRate>
<fcToBcFxRate>1.0000000000</fcToBcFxRate>
<transactionType>S</transactionType>
<invoiceDate>2013-12-26</invoiceDate>
<utcFirstCreated>2013-12-26T08:12:22</utcFirstCreated>
<utcLastModified>2013-12-26T08:12:22</utcLastModified>
<summary />
<invoiceNumber>W101010101</invoiceNumber>
发票目标代码片段
[XmlRoot(ElementName = "invoice")]
public class InvoiceDto : TransactionDto
{
public InvoiceDto()
{
TradingTerms = new TradingTermsDto();
QuickPayment = new QuickPaymentDto();
}
public InvoiceDto(string transactionType, string layout)
{
Layout = layout;
TransactionType = transactionType;
TradingTerms = new TradingTermsDto();
QuickPayment = new QuickPaymentDto();
}
[XmlElement(ElementName = "transactionType")]
public string TransactionType;
[XmlElement(ElementName = "invoiceType")]
public string InvoiceType;
[XmlElement(ElementName = "contactUid")]
public int ContactUid;
[XmlElement(ElementName = "shipToContactUid")]
public int ShipToContactUid;
[XmlElement(ElementName = "externalNotes")]
public string ExternalNotes;
我的代码:
Dim list As XmlDocument = proxy.Find(queries)
'Deserialize text file to a new object.
Using reader As XmlReader = XmlReader.Create(New StringReader(list.InnerXml))
reader.MoveToContent()
reader.Read()
reader.Read()
theinv = DirectCast(New XmlSerializer(GetType(Dto.InvoiceDto)).Deserialize(reader), Dto.InvoiceDto)
Debug.Write(theinv.InvoiceNumber)
错误是:
System.Xml.dll中发生了类型为'System.InvalidOperationException'的未处理异常
附加信息:XML文档(1,74)中有错误。
最简单的方法是创建一个类,该类从根目录开始向下匹配整个XML文档。它不需要为每个节点都包含一个属性,但是它至少需要为路径中的每个元素都包含一个属性,以便从根元素一直到您所关心的元素。例如,以下类将在您的示例中加载文档:
[XmlRoot("invoiceListResponse")]
public class InvoiceListResponse
{
[XmlArray("invoiceList")]
[XmlArrayItem("invoiceListItem")]
public InvoiceDto[] InvoiceList;
}
然后,您可以像这样反序列化它:
XmlSerializer s = new XmlSerializer(typeof(InvoiceListResponse));
using (FileStream f = new FileStream("Test.xml", System.IO.FileMode.Open))
{
InvoiceListResponse response = (InvoiceListResponse)s.Deserialize(f);
}
编辑
根据下面的评论,您似乎需要做的是反序列化为该DTO类,而无需对其进行任何修改。如果是这种情况,并且您不想创建第一个示例中展示的包装器类,则始终可以执行以下操作:
Dim invoices As New List(Of InvoiceDto)()
Dim serializer As New XmlSerializer(GetType(InvoiceDto))
For Each i As XmlNode In doc.SelectNodes("/invoiceListResponse/invoiceList/invoiceListItem")
Using reader As New StringReader("<invoice>" & i.InnerXml & "</invoice>")
invoices.Add(DirectCast(serializer.Deserialize(reader), InvoiceDto))
End Using
Next
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句