我有这个 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 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 个房间,但我应该得到两个。如果这是使用 LINQ to xml 的正确方法,请提出建议,我是 LINQ 的新手。
最佳答案
将 sections
和 rooms
查询更改为:
var sections = xDoc.Descendants("Department")
.FirstOrDefault(x => (string)x.Element("id") == "001")
.Elements("Section");
var rooms = sections.Where(x => (string)x.Element("SectionId") == "001001")
.Elements("Room");
有了这些,您将获得 2 个房间。
为什么您的代码不起作用?
select el.Element("Section")
仅选择Department
中的第一个section
元素 - 你永远无法获得空间来自部分
,id == "001002"
select el.Element("Room")
inrooms
查询仅返回每个匹配部分的第一个房间。
您可以将 Element
更改为 Elements
并添加额外的 SelectMany(x => x)
调用以使基于语法的查询有效:
var sections = from el in xDoc.Descendants("Department")
where el.Element("id").Value.Equals("001")
select el.Elements("Section");
var rooms = from el in sections.SelectMany(x => x)
where el.Element("SectionId").Value.Equals("001001")
select el.Elements("Room");
var roomsList = (from el in rooms.SelectMany(x => x)
select new
{
roomID = (string)el.Element("RoomID"),
owner = (string)el.Element("Owner")
}).ToList();
关于c# - LINQ to XML 查询返回错误数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18268870/