2

私はここに来たばかりです-そして、あなたたちが最高だと思います-だから、ここに行きます.

これが私の問題です。データベースを使わずに、あえて XML のみに基づいて完全なブログ サイトを作成しました。これまでのところ、私はとてもうまくやっています。このプロジェクトをまとめて完了するのを妨げている問題が 1 つだけあります。

次のような「ブログ コメント」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 ノード (?) に添付されたコメントの数をカウントできるようにしたいと考えています。

これまでのところ、ドキュメントを開いて読むことはできますが、数え方がわかりません....

4

3 に答える 3

1
var count = XDocument
     .Load("c://blog.xml")
     .XPathSelectElements("//comments/blogId[@id='123']")
     .Count();
于 2012-10-06T02:26:32.383 に答える
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);
于 2012-10-06T02:35:03.893 に答える
0

LINQを使用している場合は、簡単なクエリを実行できますdoc.Descendants("Comment").Count(x => x.Attributes["id"] == "123")

Visual Studioなしでこれを書いていますが、属性のアドレスが少し異なる場合があります。このコードをより頻繁に使用する場合は、基本的なエラー処理を追加することを検討してください(つまり、「id」属性は存在しません)。

于 2012-10-06T02:24:07.927 に答える