我正在尝试使用Linq查询一些XML数据,因为它比使用XPath更容易,并且作为我的同事关于如何使用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#代码(忽略Conversions类;如果该项为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中测试了这个相同的代码(返回一个匿名类而不是一个实际实体)它返回正确数量的值,但这里的代码不返回任何对象。
有什么想法吗?
答案 0 :(得分:1)
错误可能在于您首先获得accessorialsXml
的方式。尝试在执行查询之前输出此对象的内容,以确保它与您在LINQPad中使用的字符串完全相同。