Skip to main content
 首页 » 编程设计

c#之如何使用 C# 正确解析此 XML

2024年02月20日16sxdcgaq8080

我有以下 XML 代码:

<Presets> 
  <Preset ID="0" Name="aaaa"> 
    <IncludedChampions> 
      <ID>5</ID> 
      <ID>6</ID> 
      <ID>7</ID> 
    </IncludedChampions> 
  </Preset> 
  <Preset ID="1" Name="some"> 
    <IncludedChampions> 
      <ID>4</ID> 
      <ID>5</ID> 
      <ID>6</ID> 
    </IncludedChampions> 
   </Preset> 
</Presets> 

我正在尝试用这个解析它:

XmlReader reader = XmlReader.Create("./config.xml"); 
while (reader.Read()) 
{ 
   while (reader.ReadToFollowing("Preset")) 
   { 
       presetList.Add(new Preset()); 
       presetList[presetList.Count - 1].name = reader.GetAttribute(1); 
       Console.WriteLine("Preset list ID " + Convert.ToString(presetList.Count - 1)); 
 
      while (reader.ReadToFollowing("ID")) 
      { 
         Console.WriteLine("Champion ID " + reader.ReadElementContentAsString()); 
      } 
   } 
} 

但在输出中,我只看到“预设列表 ID 0”,然后是所有 ID。另一个预设 ID 去哪儿了?谢谢!

请您参考如下方法:

XmlReader.ReadToFollowing记录如下:

Reads until an element with the specified qualified name is found.

现在,从第一个预设中的 ID 7 开始,名称为“ID”的“下一个后续元素”是什么?它的 ID 4,当然...它不仅搜索 sibling 。

正如 Nick 所建议的那样,使用 LINQ to XML 会使这一切变得更简单......或者甚至只是 XmlDocument 模型,如果你真的坚持使用 .NET 2。

这是相关的 LINQ to XML 代码:

XDocument doc = XDocument.Load("config.xml"); 
foreach (var element in doc.Descendants("Preset")) 
{ 
    var preset = new Preset { name = element.Attribute("Name").Value }; 
    presetList.Add(preset); 
    Console.WriteLine("Preset list ID " + preset); 
    foreach (var id in element.Descendants("ID")) 
    { 
        Console.WriteLine(id.Value); 
    } 
}