2016-06-29 54 views
0

我有一個簡單的XML閱讀器,它使用DOM方法讀取XML文件。問題是,我在這個特定的XML文件中有兩個產品,但它只顯示第二個產品(請參閱InvoiceItem框)。我很確定我在某個地方犯了一個愚蠢的錯誤,但我只是沒有看到它。C#DOM XML解析器顯示1項而不是2

結果: Result of parsing

的源代碼:http://pastebin.com/Rh1PF92N

XML:

<?xml version="1.0" encoding="utf-8" ?> 
<Invoices> 
    <Invoice ID="I1">  
    <InvoiceDate>21/06/2016</InvoiceDate> 
    <SellerID>Supp001</SellerID> 
    <BuyerID>WCS1810</BuyerID> 
    <OrderID>O1</OrderID> 
    <InvoiceItem> 
     <Product ID="R1"> 
     <ProductName>8GB RAM King</ProductName> 
     <Description>8GB RAM King Brand</Description> 
     <Capacity>8GB</Capacity> 
     <Quantity>150</Quantity> 
     <UnitPrice>100</UnitPrice> 
     </Product> 
     <Product ID="R2"> 
     <ProductName>4GB RAM King</ProductName> 
     <Description>4GB RAM King Brand</Description> 
     <Capacity>4GB</Capacity> 
     <Quantity>100</Quantity> 
     <UnitPrice>50</UnitPrice> 
     </Product>  
    </InvoiceItem> 
    <ShippingCharges>5</ShippingCharges> 
    <InvoiceTotal>205</InvoiceTotal> 
    </Invoice> 
</Invoices> 

回答

1

在你foreach (XmlNode node2 in productList)您通過這兩種產品,但其填充invoiceItem並將其添加到invoiceItems代碼迭代是外的foreach循環,所以當foreach循環完成時,您只將循環中的最後一個元素添加到invoiceItems。 把所有的代碼放入產品foreach

invoiceItem = new InvoiceItem(); 
invoiceItem.InvoiceID = node.Attributes[0].Value; 
invoiceItem.ProductID = prodID; 
invoiceItem.Description = description; 
invoiceItem.Capacity = capacity; 
invoiceItem.Quantity = qty; 
invoiceItem.UnitPrice = unitpx; 
invoiceItem.TotalPrice = (qty * unitpx); 
invoiceItems.Add(invoiceItem);