[英]LINQ to XML extract based on condition
I have the following repetitive XML structure from which I have to create a List of an object: 我具有以下重复的XML结构,必须从中创建一个对象列表:
<entries>
<entry>
<start>2013-10-01T00:00:00.000+02:00</start>
<end>2013-11-01T00:00:00.000+02:00</end>
<value>27.02</value>
<isExtracted>true</isExtracted>
</entry>
<entry>
<start>2013-11-01T00:00:00.000+02:00</start>
<end>2013-12-01T00:00:00.000+02:00</end>
<value>27.02</value>
<isExtracted>true</isExtracted>
</entry>
<entry>
<start>2013-12-01T00:00:00.000+02:00</start>
<end>2014-01-01T00:00:00.000+02:00</end>
<value>27.02</value>
</entry>
</entries>
I would like to extract only those elements that has the isExtracted xml tag! 我只想提取具有isExtracted xml标签的那些元素!
What I do at the moment is the following: 目前,我的工作如下:
var extract = xElemMaster.Elements("entries").Elements("entry")
.Where(elem => elem.Name.Equals("isExtracted"));
But I'm not getting any results out. 但是我没有得到任何结果。 What might have probably gone wrong? 可能出了什么问题?
You can use Any
method 您可以使用Any
方法
xElemMaster.Elements("entries")
.Elements("entry")
.Where(elem => elem.Elements("isExtracted").Any());
Or just try to get element and check for null: 或者只是尝试获取element并检查null:
xElemMaster.Elements("entries")
.Elements("entry")
.Where(elem => elem.Element("isExtracted") != null);
To make it more readable I would create an extension method and use it instead: 为了使其更具可读性,我将创建一个扩展方法并改为使用它:
public static bool HasElement(this XElement source, string elementName)
{
return source.Element(elementName) != null;
}
xElemMaster.Elements("entries")
.Elements("entry")
.Where(elem => elem.Element.HasElement("isExtracted"));
You can search nodes and subnodes with Descendants
, then use Any
to check if IsExtracted exists. 您可以使用Descendants
搜索节点和子节点,然后使用Any
检查IsExtracted是否存在。
var extract = xElemMaster.Descendants("entry")
.Where(w=>w.Elements("isExtracted").Any())
You might also want to check if isExtracted==True or false 您可能还想检查isExtracted == True或false
var extract = x.Descendants("entry")
.Where(w => w.Elements("isExtracted").Any() && w.Element("isExtracted").Value=="true");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.