LINQ to XML查询返回错误数据 [英] LINQ to XML query returning wrong data
本文介绍了LINQ to XML查询返回错误数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个xml
<?xml version="1.0" encoding="utf-8" ?>
<Departments>
<Department>
<id>001</id>
<Section>
<SectionId>001001</SectionId>
<Room>
<RoomID>001001001</RoomID>
<Owner>guest1</Owner>
</Room>
<Room>
<RoomID>001001002</RoomID>
<Owner>guest11</Owner>
</Room>
</Section>
<Section>
<SectionId>001002</SectionId>
<Room>
<RoomID>001002001</RoomID>
<Owner>guest2</Owner>
</Room>
</Section>
</Department>
</Departments>
这是我使用Linq到Xml的代码
and this is my code using Linq to Xml
var xDoc = XDocument.Load(inputUrl);
var sections = from el in xDoc.Descendants("Department")
where el.Element("id").Value.Equals("001")
select el.Element("Section");
var rooms = from el in sections
where el.Element("SectionId").Value.Equals("001001")
select el.Element("Room");
var roomsList = (from el in rooms
select new Room
{
roomID = (string)el.Element("RoomID"),
owner = (string)el.Element("Owner")
}).ToList();
我的问题是列表中只有1个房间,但我应该有2个房间.还请告知这是否是使用LINQ到xml的正确方法,我对LINQ还是很陌生.
My problem is I only get 1 room in the List,but I should get two.Please also advice if this is the right way of using LINQ to xml,I am fairly new to LINQ.
推荐答案
只是为了说明有很多方法可以给猫蒙皮:
Just to show that there are many ways to skin a cat:
var xDoc = XDocument.Load(@"C:\TEST\TEST.XML");
var depts = from e in xDoc.Descendants("Department")
where e.Element("id").Value.Equals("001")
select e;
var sections = from e in depts.Descendants("Section")
where e.Element("SectionId").Value.Equals("001001")
select e;
var rooms = (from e in sections.Descendants("Room")
select new //Room
{
ID = (string)e.Element("RoomID"),
Owner = (string)e.Element("Owner")
}).ToList();
这篇关于LINQ to XML查询返回错误数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文