gpt4 book ai didi

c# - LINQ to XML 查询返回错误数据

转载 作者:太空宇宙 更新时间:2023-11-03 20:13:45 25 4
gpt4 key购买 nike

我有这个 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 的新手。

最佳答案

sectionsrooms 查询更改为:

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 个房间。

为什么您的代码不起作用?

  1. select el.Element("Section") 仅选择 Department 中的第一个 section 元素 - 你永远无法获得空间来自部分id == "001002"
  2. select el.Element("Room") in rooms 查询仅返回每个匹配部分的第一个房间。

您可以将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com