Mark Bogner
Mark Bogner

Reputation: 471

How To Count Number Of Items In XML Doc

I'm new here - and I guess you guys are the best - so here goes.

Here's my problem. I was dared to create an entire blog site based solely on XML - no databases. So far, I'm doing very well. I just have one issue that is holding me back from finishing this project all together.

I have a "Blog Comments" xml document like this:

<comments>
    <blogId id="123">
        <commentID>46</commentID>
        <userName>user1</userName>
        <userComment>This is a test comment</userComment>
    </blogId>
</comments>
<comments>
    <blogId id="123">
        <commentID>47</commentID>
        <userName>user2</userName>
        <userComment>this is a test comment by some user</userComment>
    </blogId>
</comments>
<comments>
    <blogId id="1244">
        <commentID>129</commentID>
        <userName>user3</userName>
        <userComment>This is someone else's comment</userComment>
    </blogId>
</comments>

I would like to be able to count the number of comments attached to the first blogId node(?).

So far, I have opened the doc and am able to read, but I don't know how to count.... Thoughts?

Upvotes: 2

Views: 2971

Answers (3)

RLS
RLS

Reputation: 311

var count = XDocument
     .Load("c://blog.xml")
     .XPathSelectElements("//comments/blogId[@id='123']")
     .Count();

Upvotes: 1

Tim S.
Tim S.

Reputation: 56536

XDocument doc = //your xml document

//to get the count of comments with the first id:
var blogs = doc.Descendants("blogId");
var firstId = blogs.First().Attribute("id").Value;
int count = blogs.Count(x => x.Attribute("id").Value == firstId);

//this seems more useful to me:
var commentsByBlogId = doc.Descendants("blogId").GroupBy(x => x.Attribute("id").Value);

Upvotes: 1

Zebi
Zebi

Reputation: 8882

If you are using LINQ you can do a simple query doc.Descendants("Comment").Count(x => x.Attributes["id"] == "123").

I am writing this without Visual Studio, the attribute may be addressed a little differently and if you want to use this code more often you should consider adding basic error handling (i.e. the "id" attribute does not exist).

Upvotes: 0

Related Questions