Getting the count of tags in a XML-file

  • Thread starter Thread starter K Viltersten
  • Start date Start date
K

K Viltersten

I'm using the following approach to ensure that there's
at most one tag of type blopp.

XElement element = ...;
if (element.Elements("blopp").Count > 1) {...}

However, intellisense tells me that there's no Count
property for the object. How can i get the number
of elements in the object element?
 
K said:
I'm using the following approach to ensure that there's
at most one tag of type blopp.

XElement element = ...;
if (element.Elements("blopp").Count > 1) {...}

However, intellisense tells me that there's no Count
property for the object. How can i get the number
of elements in the object element?

If you simply want to check there is at least one item then use
if (element.Elements("blopp").Any())

If you really need the complete count then use the Count method e.g.
if (elements.Elements("blopp").Count() == 5)
 
I'm using the following approach to ensure that there's
If you simply want to check there is at least one item then use
if (element.Elements("blopp").Any())

If you really need the complete count then use the Count method e.g.
if (elements.Elements("blopp").Count() == 5)

It seems that there's no Count nor Count() for the
object returned by .Elements(). Suggestions?

I've tried the following:

XElement elem;
elem.Elements().Count; // error
elem.Elements().Count(); // error
 
K Viltersten pretended :
It seems that there's no Count nor Count() for the
object returned by .Elements(). Suggestions?

I've tried the following:

XElement elem;
elem.Elements().Count; // error
elem.Elements().Count(); // error

a guess:

add a "using System.Linq;" at the top of your file.

The Count method is not implemented by XElement itself, rather it is an
extension method declared in the System.Linq namespace (in the
Enumerable class).

Hans Kesting
 
I'm using the following approach to ensure that there's
a guess:

add a "using System.Linq;" at the top of your file.

The Count method is not implemented by XElement itself, rather it is an
extension method declared in the System.Linq namespace (in the Enumerable
class).

Good guess. However, when i added that, it required me to
reference Core.dll and THEN i get the info that it's a C#3.0
feature... Sigh...

Am i to understand that DotNet2.0 doesn't allow for simple
counting of the elements in an IEnumerable object?!
 
K said:
Am i to understand that DotNet2.0 doesn't allow for simple
counting of the elements in an IEnumerable object?!

I guess when you are using .NET 2.0, you have to use XPath, like

XmlDocument doc = ...;
if (doc.SelectNodes("//blob").Count > 1)
....
 
Back
Top