我需要将xml数据加载到newtonsoft jobject中,并查询特定名称&值节点...
这只是一个简化的示例,问题是在最后一行中,即使有一个我正在寻找的ID的exturanfirstlevel元素的孩子,结果效果是无效的...
示例:
int idFirst = 2;
int idSecond = 4;
string json = string.Empty;
JObject jFirstLevels = new JObject();
string xml = "<Root><FirstLevel id="1"><Secondlevel id="1" value="hello11" /><Secondlevel id="2" value="hello12" /><Secondlevel id="3" value="hello13" /></FirstLevel><FirstLevel id="2"><Secondlevel id="4" value="hello24" /></FirstLevel><FirstLevel id="3"><Secondlevel id="5" value="hello35" /><Secondlevel id="6" value="hello36" /><Secondlevel id="7" value="hello37" /></FirstLevel></Root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNodeList nodeList;
nodeList = xmlDoc.SelectNodes("Root/FirstLevel");
if (nodeList != null)
{
if (nodeList.Count > 1)
{
JArray jarray = new JArray();
foreach (XmlNode node in nodeList)
{
json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(node);
jarray.Add(JObject.Parse(json));
}
jFirstLevels["result"] = jarray;
}
}
JObject resultFirstLevel = jFirstLevels["result"].Children<JObject>().FirstOrDefault(x => x["FirstLevel"]["@id"].Value<int>() == idFirst);
JObject resultSecondLevel = resultFirstLevel.Children<JObject>().FirstOrDefault(x => x["SecondLevel"]["@id"].Value<int>() == idSecond);
这是因为您在ResultFirstLevel中获得了Jproperty的列表。
您需要使用此代码进行切换,例如:
JObject resultFirstLevel = jFirstLevels["result"].Children<JObject>().FirstOrDefault(x => x["FirstLevel"]["@id"].Value<int>() == idFirst);
var firstlevelProperty = resultFirstLevel.Children().Cast<JProperty>().Select(x => x.Value);
var resultSecondLevel = firstlevelProperty.FirstOrDefault(x => x["Secondlevel"]["@id"].Value<int>() == idSecond);
(此外,您输入的XML和测试之间还有一个错别字:它是" secives velvel"," sequient",较低的" L")