I have following xml result
<?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>
I have following class
public class Result{
public string SearchValue {get;set;}
public string SearchResult {get;set;}
}
And this code
...
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
});
}
...
How to get all searched keys and searched result to list object?
>Solution :
I suspect you want something like:
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();
That assumes that:
- You only care about elements that are direct children of the root element
- You want to ignore any elements whose local names don’t start with "QUERY"
- You’re okay with handling a missing
searchedattribute by creating aResultobject with a null value forSearchValue - You’re okay with
SearchResultbeing the concatenation of all text nodes in the query element