使用 Linq to Xml 获取 Xml 属性的值

Get value of an Xml attribute using Linq to Xml

我有一个 XML 这样的:

<?xml version="1.0" encoding="utf-8"?>
<Projects>
  <Project>
    <Name>Projekt0</Name>
    <Information>
      <Version>1.0</Version>
      <Info>test-project</Info>
      <CreateDate>25.02.2015</CreateDate>
    </Information>
    <Files ID="1" path="D:\Data\ID1">
      <file>one_file</file>
      <file>another_file</file>
    </Files>
    <Files ID="2" path="D:\Data\ID2">
      <file>someFile.txt</file>
    </Files>
  </Project>
</Projects>

它包含更多 "Project" 个节点,但这不是必需的。

首先,我 select 一个特定项目的名称。这已经有效,并且是这样完成的:

var entries = from items in xelement.Elements("Project")
                      where (string)items.Element("Name").Value == projectName
                      select items;

条目现在包含了想要的项目的所有内容。

我的方法之一需要知道两个 "Files" 节点的路径值。 我已经试过了,但还是不行。

我的第一个尝试是创建一个新的 'var',例如 'entries',将其转换为数组,然后 selecting 索引以将值保存为字符串。

var path1 = from item in entries.Elements("Files")
            where (string)item.Attribute("ID").Value == "1"
            select item.Attribute("path").Value;
string path01 = path1.toArray()[0];

这不起作用,我不确定为什么。如果这是初学者的问题,我很抱歉,但我还没有对 xml 和 linq 做很多事情。

编辑:

下面的'entries'变量是第一个linq代码的输出。所以 'entries' 包含一个完整的项目。 当前,path1 不包含任何元素。

entries 是项目节点的序列。搜索ID属性前取Files子节点

var path1 = from item in entries.Elements("Files")
        where (string)item.Attribute("ID").Value == "1"
        select item.Attribute("path").Value;