[英]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>
它包含更多的“项目”节点,但这不是必需的。
首先,我通过名称选择一个特定的项目。 这已经有效,并且可以通过以下方式完成:
var entries = from items in xelement.Elements("Project")
where (string)items.Element("Name").Value == projectName
select items;
条目现在包含所需项目的所有内容。
我的一种方法需要知道两个“文件”节点的路径值。 我已经尝试过一些东西,但是还不能正常工作。
我的第一个尝试是创建一个新的'var',例如'entries',将其转换为数组,然后选择索引以将值保存为字符串。
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代码的输出。 因此,“条目”包含整个项目。 当前,path1不包含任何元素。
entries
是项目节点的序列。 在搜索ID属性之前,先获取“文件”子节点
var path1 = from item in entries.Elements("Files")
where (string)item.Attribute("ID").Value == "1"
select item.Attribute("path").Value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.