Skip to main content
 首页 » 编程设计

c#之为 C# 应用程序建模 XML 数据

2024年02月05日8lyj

我遗漏了一个关于在 XML 中建模数据的概念。考虑以下 XML,它将保存我正在编写的应用程序的一些配置数据。

 <?xml version="1.0" encoding="utf-8"?> 
<DateGuessConfigValues> 
  <Players> 
    <Player Id="1"> 
      <Name>Yusnier Viera</Name> 
      <Country>Cuba</Country> 
    </Player> 
    <Player Id="2"> 
      <Name>Ron White</Name> 
      <Country>USA</Country> 
    </Player>     
  </Players> 
  <Centuries> 
    <Century>1900</Century> 
    <Century>2000</Century> 
  </Centuries> 
</DateGuessConfigValues> 

我将此 XML 存储在名为“DateGuessConfig.xml”的文件中,然后运行以下程序...

using System; 
using System.Xml.Linq; 
using System.Linq; 
 
class Program 
{ 
    public static void Main(String[] args) 
    { 
        String strPath = @"C:\XMLExample\DateGuessConfig.xml"; 
        XElement xEle = XElement.Load(strPath);     
        var query = xEle.Descendants("Centuries").ToList();     
        foreach (var c in query) 
        { 
            Console.WriteLine(c.Element("Century").Value); 
        } 
        Console.WriteLine("Press <enter> to continue"); 
        Console.ReadLine(); 
    } 
} 

我希望我的结果是...

1900

2000

不过我只是得到

1900

我是否错误地建模了数据?我应该使用属性而不是内部文本吗?

请您参考如下方法:

query 在您的示例中只有一个元素:Centuries 节点。您需要访问其后代。因此,在您的示例中,它经历了一次循环并检索了第一个 Century 值。

尝试用这个替换你的foreach:

 foreach (var c in query.Descendants("Century")) 
      { 
        Console.WriteLine(c.Value); 
      }