[英]Get an Array by selection of a block from xml-File
我必须使用Linq编写程序。 我只是一个学生,还没有学到,所以我有两个问题:
我有一个XML文件,看起来像这样:
<?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>
我想得到一个包含“文件”元素值的字符串数组,依赖于ID = S或C。我在那里有多个项目,因此首先必须按名称搜索,这是正确的现在:
var entries = from items in xelement.Elements("Project")
where (string)items.Element("Name").Value == projectName
select items;
这使我获得了所需项目的整个模块。 我可以使用第一个命令的结果来获取文件名吗? 还是可以仅扩展第一部分的代码?
要获得具有指定名称的特定Project
元素,可以使用First
:
var projectElement = xElement
.Elements("Project")
.First(x => (String) x.Element("Information").Element("Name").Value == projectName);
通过类似的方式,您可以通过指定ID属性的值来找到所需的Files
元素:
var filesElement = projectElement
.Elements("Files")
.First(x => x.Attribute("ID").Value == id);
然后,您可以使用Select
将File
元素投影到其值并将其转换为数组:
var files = filesElement
.Elements("file")
.Select(x => (String) x.Value)
.ToArray();
请注意,如果XML具有意外格式,则此代码将引发异常。 例如,如果First
找不到匹配的元素,则会引发异常。 另外,如果未找到指定的元素,则Element
方法将返回null
,因此,如果没有Information
元素,则x.Element("Information").Element("Name")
将引发异常,因为下一次对Element
调用对null
引用执行。
谢谢Martin,这个方法很有效:)我只是想出了一个自己的解决方案,如下所示:
var files = from file in entries.Elements("Files").Elements("file")
where (string)file.Parent.Attribute("ID").Value == cOrS
select file.Value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.