2

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.

Millet Antoine
  • 405
  • 1
  • 6
  • 24
  • Look at recursive method on following webpage : http://stackoverflow.com/questions/28976601/recursion-parsing-xml-file-with-attributes-into-treeview-c-sharp – jdweng May 24 '16 at 09:37

2 Answers2

1

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

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0
        //Use System.Xml namespace
        //Load the XML into an XmlDocument object
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(strPathToXmlFile); //Physical Path of the Xml File
        //or
        //xDoc.LoadXml(strXmlDataString); //Loading Xml data as a String

        //In your xml data - coverage is the root element (DocumentElement)
        XmlNode rootNode = xDoc.DocumentElement;

        //To get all the attributes and its values 
        //iterate thru the Attributes collection of the XmlNode object (rootNode)
        foreach (XmlAttribute attrib in rootNode.Attributes)
        {
            string attributeName = attrib.Name; //Name of the attribute - x1, x2, x3 ...
            string attributeValue = attrib.Value; //Value of the attribute

            //do your logic here 
        }

        //if you want to save the changes done to the document
        //xDoc.Save (strPathToXmlFile); //Pass the physical path of the xml file

        rootNode = null;
        xDoc = null;

Hope this helps.

  • Thank you for your answer, I wanted to try your code, but I get the error "(407) Proxy Authentication Required"), I think (I'm even pretty sure) it's because we have a proxy. So, I will continue with the previous solution, but thank you anyway for your answer. – Millet Antoine May 24 '16 at 10:13