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

标签 c# xml 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 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/

相关文章:

C#:如何使 HttpWebRequest 模仿 Web 浏览器控件

java - gwt 将新的子节点添加到 xml 文件中

python - 使用python-pptx检查powerpoint中的图像是否具有装饰性

c# - 为什么 i.Parent.ReplaceWith(i) 不抛出异常?

c# - 使用 Linq to XML 查询 google sitemap.xml 的问题

c# - 如何在 .NET 4 中使用 Console.CancelKeyPress? (在 .NET 3.5 及以下版本中工作正常)

c# - 使用 Google map 作为商店定位器

java - 将 xml 代码解码为 Java 对象的最佳方法?

c# - 将多个属性插入 XML 元素。联机SQL

c# - Task.WhenAny 会取消注册未完成任务的延续吗?