读取简单的XML文件

but夫

我正在尝试使用linq读取非常简单的xml文件。我知道如何使用子节点上的for循环来做到这一点,但我正在尝试学习linq。无论如何,我有一个文件:

<firstElement>
  <Setting Name="appDataPath" Value="some\\path" />
  <Setting Name="appConfigFileName" Value="somename.xml" />
  <Setting Name="appConfigFilePath"  Value="some\\path" />
</firstElement>

我想获取设置属性。我有以下代码:

//Load xml
XDocument xdoc = XDocument.Load(fullyQualifiedPath);

var settings = from item in xdoc.Descendants("firstElement")
     select new
     {
         name = item.Attribute("Name").Value,
         val = item.Attribute("Value").Value
     };

     // create a dictionary
     Dictionary<string, string> settingsDictionary = 
                        new Dictionary<string, string>();

   //Loop through results
   foreach (var setting in settings)
   {
      settingsDictionary.Add(setting.name, setting.val);
   }

   xdoc.Save(fullyQualifiedPath);

由于某些原因,查询后设置为null。我想念什么吗?

安东尼奥·佩莱里蒂(Antonio Pelleriti)

要仅获取设置节点,请编写:

from item in xdoc.Descendants("Setting")

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章