我有以下xml结果
<?xml version="1.0" encoding="windows-1254" ?>
<RESPONSE>
<VALIDATION>1</VALIDATION>
<QUERY1 searched="12345">0</QUERY1>
<QUERY2 searched="aaaaa">2</QUERY2>
<QUERY3 searched="44444">2</QUERY3>
<QUERY4 searched="99999">0</QUERY4>
<QUERY5 searched="number">0</QUERY5>
<QUERY6 searched="bar">0</QUERY6>
<QUERY7 searched="foo">1</QUERY7>
</RESPONSE>
</xml>
我有以下类
public class Result{
public string SearchValue {get;set;}
public string SearchResult {get;set;}
}
这个代码
...
List<Result> r = new List<Result>();
XDocument doc = XDocument.Parse(xmlResult);
foreach( var item in doc.Descendants("RESPONSE")){
r.Add(new Result{
SearchValue = item.Attribute("searched").Value,
SearchResult = item.Element("QUERY?").Value
});
}
...
如何获得所有搜索键和搜索结果列表对象?
我怀疑你想要这样的东西:
XDocument doc = XDocument.Parse(xmlResult);
var results = doc.Root
.Elements()
.Where(e => e.Name.LocalName.StartsWith("QUERY"))
.Select(e => new Result {
SearchValue = (string) e.Attribute("searched"),
SearchResult = e.Value
})
.ToList();
假设:
- 你只关心根元素 的直接子元素
- 你想忽略任何本地名称不以"QUERY"> 开头的元素
- 您可以通过为
SearchValue
创建具有空值的Result
对象来处理缺失的searched
属性。 - 您可以将
SearchResult
作为查询元素 中所有文本节点的连接
可以使用xpath//RESPONSE/*[starts-with(name(),'QUERY')]
foreach(XmlNode row in doc.SelectNodes("//RESPONSE/*[starts-with(name(),'QUERY')]"))
{
if(row.Attributes.Cast<XmlAttribute>().Any(x=>x.Name=="searched"))
{
Result r2 = new Result(){
SearchValue = row.Attributes["searched"].Value,
SearchResult = row.InnerText
};
r.Add(r2);
}
}
LINQ重写
var nodes = doc.SelectNodes("//RESPONSE/*[starts-with(name(),'QUERY')]")
.Cast<XmlNode>();
//.SelectMany(x=>x.ChildNodes.Cast<System.Xml.XmlElement>());
var query = (from elm in nodes
where elm.Attributes.Cast<XmlAttribute>().Any(x=>x.Name=="searched")
select new Result(){
SearchValue = elm.Attributes["searched"].Value,
SearchResult = elm.InnerText
}).ToList();
https://dotnetfiddle.net/RMxEiT您可以将其转换为json对象并使用Linq
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlResult);
var jObj = JObject.Parse(JsonConvert.SerializeXmlNode(xmlDoc));
List<Result> results = ((JObject)jObj["RESPONSE"]).Properties()
.Where(v => v.Name.StartsWith("QUERY"))
.Select(v => new Result
{
SearchValue = (string)v.Value["@searched"],
SearchResult = (string)v.Value["#text"]
}).ToList();