2014-02-24 106 views
0

我是新来的linq到xml(linq任何东西,对于这个问题),我试图计算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,因为我不想计算空的元素。

+0

当你说元素没有价值。你什么意思?绑定是一个元素,并没有一个值。你的意思是一本书的元素? – 2014-02-24 23:27:06

+0

我的意思是一个特定的元素,在这种情况下,。正如你可以看到我的XML,第二本书有一个元素没有价值。我想要返回一切,但那一个。假设xml数量更多,有数千本书,我想返回所有元素,除了所有没有价值的元素。所以伪代码可能是“读取xml文件减去元素名称”绑定“值为空”。 – u84six

+0

我明白了。下面的任何解决方案都可以工作。然而,如果你认为一个元素可能包含空格,那么你需要使用下面的我的版本(string.IsNullOrWhiteSpace)。如果你需要这两个元素和他们的计数,那么你应该使用.ToList()然后访问.Count属性。 – 2014-02-25 03:02:23

回答

0

我没有尝试,但是这会工作:

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

如果您希望元素只是用Where代替Count

2
int count = XDocument.Load(@"C:\books.xml") 
      .Descendants() 
      .Where(x => !String.IsNullOrWhiteSpace(x.Value)) 
      .Count(); 
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(); 
+0

如果您的XML内容不是很大,那么在性能方面就会好。 – 2014-02-25 20:07:32

相关问题