返回除了没有值的特定元素之外的所有元素

时间:2014-02-24 23:21:04

标签: c# linq

我是linq to xml的新手(linq to any,就此而言),我正在尝试计算xml文件中的元素数量但排除了一些。这是一个例子:

<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
      <binding>paperback</binding>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
      <binding></binding>
   </book>
</catalog>

鉴于上面的xml,我想返回除了没有值的元素之外的所有元素。因此,在这种情况下,结束计数将为16,因为我不想计算空元素。

3 个答案:

答案 0 :(得分:2)

 int count  = XDocument.Load(@"C:\books.xml")
            .Descendants()
            .Where(x => !String.IsNullOrWhiteSpace(x.Value))
            .Count();

答案 1 :(得分:0)

我没试过,但这会奏效:

var xDoc = XDocument.Load("path");
var count = xDoc.Descendants()
            .Count(x => !string.IsNullOrEmpty((string)x));

如果您想要元素,请使用Where代替Count

答案 2 :(得分:0)

这是我使用所有帮助想出来的。不确定它是否非常有效,但它确实有效:

XDocument doc = XDocument.Load(@"C:\books.xml");
var elementList = doc.Descendants().ToList();
int count = elementList.Count();
count -= elementList.Where(x => x.Name == "binding" && String.IsNullOrEmpty(x.Value)).Count();