如何计算XML Doc中的项目数

时间:2012-10-06 02:19:12

标签: c# asp.net xml

我是新来的 - 我猜你们是最好的 - 所以这里就是。

这是我的问题。我敢于创建一个完全基于XML的博客网站 - 没有数据库。到目前为止,我做得很好。我只有一个问题阻碍了我完成这个项目。

我有一个像这样的“Blog Comments”xml文档:

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

我希望能够计算附加到第一个blogId节点(?)的注释数量。

到目前为止,我已经打开了文档并且能够阅读,但我不知道如何计算.... 想法?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如果您使用的是LINQ,则可以进行简单的查询doc.Descendants("Comment").Count(x => x.Attributes["id"] == "123")

我在没有Visual Studio的情况下写这个,属性可能会有所不同,如果你想更频繁地使用这个代码,你应该考虑添加基本的错误处理(即“id”属性不存在)。

答案 2 :(得分:0)

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