![](/img/trans.png)
[英]Need help selecting the second child node and it's children with XPath in C#
[英]c# json count node's children
為了澄清我的問題,我想使用Namespace: Newtonsoft.Json.Linq
JToken.SelectTokens Method (String)
。 如何使用方法SelectTokens("")
獲取每個節點"174637"
(unit_id)和"174638"
(unit_id)的子代數? 對於第一個節點,我應該得到1
,對於第二個節點,我應該得到2
。 我已經試過像這樣:
foreach (var test in unit_ids) { //takes every unit_id, one by one
var children_of_unit_id = test.SelectTokens("*.[*]").count();
}
但是它什么也沒有給我。
"174637": {
"1": {
"value_symbol": "3",
"exam_session_number": 1,
"exam_id": 207983,
"value_description": {
"en": "satisfactory",
}
}
}
"174638": {
"1": {
"value_symbol": "3",
"exam_session_number": 1,
"exam_id": 207984,
"value_description": {
"en": "satisfactory",
}
}
"2": {
"value_symbol": "3",
"exam_session_number": 2,
"exam_id": 207985,
"value_description": {
"en": "satisfactory",
}
}
}
EDITED
這是原始的Json
:
{
"grades": {
"course_units_grades": {
"173565": {
"1": {
"value_symbol": "3,5",
"exam_session_number": 1,
"exam_id": 208798,
"value_description": {
"en": "satisfactory plus",
"pl": "dst+"
}
}
},
"173566": {
"1": {
"value_symbol": "2",
"exam_session_number": 1,
"exam_id": 208797,
"value_description": {
"en": "unsatisfactory",
}
},
"2": {
"value_symbol": "3",
"exam_session_number": 2,
"exam_id": 208797,
"value_description": {
"en": "satisfactory",
}
}
}
},
"course_grades": {}
}
}
所以看起來像這樣:
foreach (var t in json_grade)//take every "grades" element, one by one
{
var test = t.SelectTokens("['grades'].['course_units_grades']");
foreach (var unit_ids in test)
{
foreach (var test in unit_ids) { //takes every unit_id, one by one
var children_of_unit_id = test.SelectTokens("*.[*]").count();
}
}
}
嘗試這個:
var token = JToken.Parse(j)["unit_id"][0].ToList().Count;
樣本JSON:
{
"174637": [
{
"1": {
"value_symbol": "3",
"exam_session_number": "1",
"exam_id": "207983",
"value_description": {
"en": "value_description"
}
}
}
],
"174638": [
{
"1": {
"value_symbol": "3",
"exam_session_number": "1",
"exam_id": "207983",
"value_description": {
"en": "value_description"
}
},
"2": {
"value_symbol": "3",
"exam_session_number": "1",
"exam_id": "207983",
"value_description": {
"en": "value_description"
}
}
}
]
}
您可以嘗試以下兩種方式之一:
foreach (var test in unit_ids)
{
var approach1 = test.Children().Children().Count();
var approach2 = test.First.SelectTokens("*").Count();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.