0
我想要使用Linq來查詢一些XML數據,因爲它比使用XPath更容易,並且作爲我的同事的一個很好的「概念驗證」可以使用Linq。下面是我的XML:當XML中有項目時,Linq到XML不返回任何項目
<Booking>
<ServiceCollection>
<Service>
<BookingID>10508507</BookingID>
<AdditionalChargeID>1</AdditionalChargeID>
<ServiceName>Fuel Surcharge</ServiceName>
<ServiceCost>56.87</ServiceCost>
<ServiceCharge>103.41</ServiceCharge>
<showInNotes>0</showInNotes>
<showInHeader>0</showInHeader>
<BOLHeaderText />
</Service>
<Service>
<BookingID>10508507</BookingID>
<AdditionalChargeID>2</AdditionalChargeID>
<ServiceName>Lift Gate at Pickup Point</ServiceName>
<ServiceCost>25.00</ServiceCost>
<ServiceCharge>42.00</ServiceCharge>
<showInNotes>1</showInNotes>
<showInHeader>1</showInHeader>
<BOLHeaderText>Lift Gate at Pickup Point</BOLHeaderText>
</Service>
</ServiceCollection>
</Booking>
現在,這裏是我的C#代碼(忽略轉換類,他們只是確保返回的默認值,如果該項目爲null):
var accessorials = from accessorial in accessorialsXml.Elements("ServiceCollection").Elements("Service")
select new Accessorial
{
BookingID = Conversions.GetInt(accessorial.Element("BookingID").Value),
Name = accessorial.Element("ServiceName").Value,
Cost = Conversions.GetDecimal(accessorial.Element("ServiceCost").Value),
Charge = Conversions.GetDecimal(accessorial.Element("ServiceCharge").Value),
ShowInNotes = Conversions.GetBool(accessorial.Element("showInNotes").Value),
ShowInHeader = Conversions.GetBool(accessorial.Element("showInheader").Value),
BillOfLadingText = accessorial.Element("BOLHeaderText").Value
};
return accessorials.ToList();
我有一個單元測試失敗,因爲輔助數(XML中的「服務」節點)的計數爲0時,應該是2.我在LinqPad中測試了這個相同的代碼(返回一個匿名類而不是實際實體)正在返回適當數量的值,但此處的代碼不返回任何對象。
任何想法?
您是否嘗試過accessorialsXml.Element(「Booking」)。Elements(...)? – devdigital 2011-02-04 17:41:56
是的;這樣做會在選擇新代碼中的某處引發NullRef異常。檢查LinqPad,元素(「預訂」)返回null,因此鏈接其他觸發NullReferenceException。 – 2011-02-04 17:46:07