c# - 如何计算 XML 文档中的项目数

标签 c# asp.net xml

我是新来的 - 我猜你们是最棒的 - 所以就这样吧。

这是我的问题。我敢于完全基于 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/

相关文章:

c# - 字符串到数组?

c# - 了解 MVC 中的 [HttpPost]、[HttpGet] 和 Complex Actionmethod 参数

c# - 从对象列表中创建一个逗号分隔的字符串

asp.net core 2.0 在输出文件夹中有 Microsoft.VisualStudio.Web.CodeGeneration 文件

c# - 更改txt文件并保存的快速方法

xml - xslt中for循环的使用方法

java - Android studio "java.lang.OutOfMemoryError"模拟器 redmi 2 prime kitkat

C#:扩展的 WPF 工具包 - 在 MessageBox 中自定义按钮标签

asp.net - Stripe Webhook 事件 续订订阅

android - 将 onclick 方法更改为带有动画的大小