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.

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.