简体   繁体   中英

Get an Array by selection of a block from xml-File

I have to write a program using Linq. I'm just a student and I didn't learned that yet, so I have two questions:

  1. What would be a good book/ebook... to teach myself what my next question will be about?
  2. I have an XML-File, that looks like this:

     <?xml version="1.0" encoding="utf-8"?> <Projects> <Project> <Information> <Name>Project1</Name> <Date>26.01.2015</Date> </Information> <Files ID = "S" path = "C:\\Users\\marcel\\Documents"> <file>Test1.txt</file> <file>Test2.txt</file> <file>Test3.txt</file> <file>Test4.txt</file> <file>Test5.txt</file> </Files> <Files ID = "C" path = "C:\\Users\\marcel\\Documents"> <file>Test1(1).txt</file> <file>Test1(2).txt</file> <file>Test1(3).txt</file> <file>Test1(4).txt</file> <file>Test1(5).txt</file> </Files> </Project> 

I want to get a string-array which is containing the values of the "file" elements, depenging on ID=S or C. I have more than 1 project in there, so it first has to be searched by name, that's working right now:

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

that gets me the whole block of the needed project. Can I use the result of the first command for getting the filenames? Or can I just extend the code of the first part?

To get a specific Project element having the specified name you can use First :

var projectElement = xElement
  .Elements("Project")
  .First(x => (String) x.Element("Information").Element("Name").Value == projectName);

In a similar way you can find the desired Files element by specifying a value for the ID attribute:

var filesElement = projectElement
  .Elements("Files")
  .First(x => x.Attribute("ID").Value == id);

You can then use Select to project the File elements to their values and convert that to an array:

var files = filesElement
  .Elements("file")
  .Select(x => (String) x.Value)
  .ToArray();

Note that this code will throw exceptions if the XML has an unexpected format. Eg, if First does not find a matching element an exception is thrown. Also, the Element method will return null if the specified element is not found and thus code like x.Element("Information").Element("Name") will throw an exception if there is no Information element because the next call to Element is performed on the null reference.

Thank you Martin, that worked :) I just came up with an own solution looking like this:

var files = from file in entries.Elements("Files").Elements("file")
                        where (string)file.Parent.Attribute("ID").Value == cOrS
                        select file.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