Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to foreach following xml in c#

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

...
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 searched attribute by creating a Result object with a null value for SearchValue
  • You’re okay with SearchResult being the concatenation of all text nodes in the query element
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading