我是新来的 - 我猜你们是最棒的 - 所以就这样吧。
这是我的问题。我敢于完全基于 XML 创建整个博客网站 - 没有数据库。到目前为止,我做得很好。我只有一个问题阻碍我完成这个项目。
我有一个像这样的“博客评论”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 节点的评论数量(?)。
到目前为止,我已经打开了文档并且能够阅读,但我不知道如何计数...... 想法?
最佳答案
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);
关于c# - 如何计算 XML 文档中的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12756129/