我需要将xml数据加载到newtonsoft JObject中并查询特定名称&值节点......
这只是一个简化的示例,问题出现在最后一行代码中,即使有一个带有我正在寻找的ID的resultFirstLevel的子元素,resultSecondLevel也为null ...
示例:
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);
答案 0 :(得分:0)
这是因为你在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和你的测试之间有一个拼写错误:它是“Secondlevel”,低于“l”)