使用C#使用XMLreader读取子元素(子节点)

本文关键字:使用 子节点 元素 XMLreader 读取 | 更新日期: 2023-09-27 18:28:57

第一:这不是用XMLReader读取子节点的重复(不是同一种语言,无法帮助我)

我是XMLreading的新手,我正在尝试访问特定元素的子元素,但我很难访问它,下面是一个示例:

XML元素:

<Group ExerciseNumber="0" Name="R33-IOS1_IOS1" ExerciseName="Unallocated" Status="offline" StatusStatistics="0/1">
      <Clients>
        <Client ClientName="R33-IOS1_IOS1" MachineName="R33-IOS1" ClientType="HC0" ClientStatus="Disconnected" />
      </Clients>
      <GroupAppendedData GroupID="201" Type="IOS" DomeType="None" ConnectedTo="" ForceType="Enemy" />
    </Group>

我正试图从特定的"组"元素到达"客户端"元素,这是我的C#代码:

while (reader.Read())
            {
                if (reader.Name.Equals("Group"))
                {
                    name = reader.GetAttribute("Name");
                    // Now I need to reach the specific "MachineName" attribute of the "Client" sub-element but don't know how.
                }
            }
            reader.Close();

注意事项:重要的是,客户端元素的读取将在同一个循环迭代中(如果可能,如果不可能,我将不得不为我的生成类考虑另一种设计)。

*编辑XML不是一个选项。

谢谢。

使用C#使用XMLreader读取子元素(子节点)

LINQ to XML比XmlReader更容易使用,这将为文档中的所有客户端提供机器名称:

var machineNames = XElement.Parse("data.xml")
                           .Descendants("Client")
                           .Select(client => client.Attribute("MachineName").Value);

编辑-这在每次迭代中都返回两个名称:

var query = XElement.Load("data.xml")
                    .Descendants("Client")
                    .Select(client => new {
                               MachineName = client.Attribute("MachineName").Value,
                               GroupName = client.Ancestors("Group").Select(g => g.Attribute("Name").Value).First()
                           });
foreach (var x in query)
    Console.WriteLine($"GroupName: {x.GroupName}, MachineName: {x.MachineName}");

根据建议,除非您有充分的理由使用XmlReader,否则最好使用更高级别的API,如LINQ to XML。

以下是使用查询语法的解决方案:

var clients = from @group in doc.Descendants("Group")
              let groupName = (string) @group.Attribute("Name")
              from client in @group.Descendants("Client")
              select new
              {
                  GroupName = groupName,
                  ClientName = (string) client.Attribute("ClientName"),
                  MachineName = (string) client.Attribute("MachineName"),
              };

请参阅此小提琴以获取工作示例。

在xml linq 中尝试ReadFrom()方法

            while (reader.Read())
            {
                if (reader.Name.Equals("Group"))
                {
                    XElement group =  (XElement)XDocument.ReadFrom(reader);
                }
            }
            reader.Close();​