简体   繁体   English

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

[英]Get value of an Xml attribute using Linq to Xml

I have an XML like this: 我有这样的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>

It contains some more "Project"-Nodes, but that's not necessary. 它包含更多的“项目”节点,但这不是必需的。

First, I select a specific project by it's name. 首先,我通过名称选择一个特定的项目。 This works already, and is done this way: 这已经有效,并且可以通过以下方式完成:

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

entries contains now all the content of the wanted project. 条目现在包含所需项目的所有内容。

One of my methods need to know the path-values of the both "Files"-Nodes. 我的一种方法需要知道两个“文件”节点的路径值。 I already tried something, but it's not working yet. 我已经尝试过一些东西,但是还不能正常工作。

My first try was creating a new 'var' like 'entries', converting that to an array, and selecting the indices for saving the values as a string. 我的第一个尝试是创建一个新的'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];

That is not working, and I'm not sure why. 那是行不通的,我不确定为什么。 I'm sorry if that is a beginners question, but I haven't done a lot with xml & linq yet. 抱歉,这是一个初学者的问题,但是我对xml&linq的处理还不够。

edit: 编辑:

The lower 'entries' variable is the output of the first linq-code. 较低的“ entries”变量是第一个linq代码的输出。 So 'entries' contains a whole project. 因此,“条目”包含整个项目。 Currently, path1 does not contain any elements. 当前,path1不包含任何元素。

entries is a sequence of Project nodes. entries是项目节点的序列。 Take Files child nodes before searching ID attribute 在搜索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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM