Search code examples
c#xml-parsingxmlreader

How to get all the key-values of the root element using c#?


I search for a few days how to parse my xml file. So my problem I will want to recover all the key-values of the root element .

Exemple of file:

<?xml version="1.0" ?>
<!DOCTYPE ....... SYSTEM ".....................">
<coverage x="y1"  x2="y2"  x3="y3"  x4="y4">
    <sources>
      <source>.............</source>
    </sources>
    .....
<\coverage>

Here, i will want to Recover all the value of "coverage" : x1 and his value , x2 and his value, x3 and his value x3... I have already tried using "XmlReader" with all the tutorial i have could find but it still does not work. All tutorials I've could tried, recover a value in a certain node (tag), but never all the values of the root element.

Maybe a tutorial with this same problem already exist but i haven't found him.

Thank you in advance for your help.


Solution

  • You could use XElement and do this.

    XElement element = XElement.Parse(input);
    
    var results = element.Attributes()
                         .Select(x=> 
                                 new 
                                 {
                                     Key = x.Name, 
                                     Value = (string)x.Value
                                 });
    

    Output

    { Key = x, Value = y1 }
    { Key = x2, Value = y2 }
    { Key = x3, Value = y3 }
    { Key = x4, Value = y4 }
    

    Check this Demo