简体   繁体   中英

Get value of an Xml attribute using Linq to Xml

I have an XML like this:

<?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 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.

edit:

The lower 'entries' variable is the output of the first linq-code. So 'entries' contains a whole project. Currently, path1 does not contain any elements.

entries is a sequence of Project nodes. Take Files child nodes before searching ID attribute

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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