Getting the count of tags in a XML-file

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?
 
M

Martin Honnen

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)
 
K

K Viltersten

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
 
H

Hans Kesting

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
 
K

K Viltersten

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?!
 
M

Martin Honnen

A

Arto Viitanen

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)
....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top