首先:这不是 Reading Child Nodes with 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>
我试图从特定的“Group”元素到达“Client”元素,这是我的 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 不是一种选择。
谢谢。
请您参考如下方法:
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}");
