To read data from xml and to store in array in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Arjun Sarankulu
    New Member
    • Jan 2011
    • 4

    To read data from xml and to store in array in C#

    I want to read numbers from XML file
    Suppose xml file contain
    <number>1</number>
    <number>10</number>
    <number>20</number>
    <number>30</number>
    <number>69</number>

    The above mention numbers in XML file, i want to store in array.
    Can any one help me for the same
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    I'm willing to bet one of the experts familiar with LINQ can come in here and post a better method (I'm pretty sure I've seen them do something like this), but the way I'm familiar with involves just parsing the XML.

    There are two classes you'll want to take a look at:
    Represents an XML document. You can use this class to load, validate, edit, add, and position XML in a document.



    That XML would be contained by some kind of parent node... I don't know what it is, but lets say it looks something like this:

    <array>
    <number>1</number>
    ...
    </array>
    In this example, you would parse your XML. If you encountered a node named array you could then call a method to parse that node. To get this into an array, it's just a matter of looping through the child nodes on that array and adding their values to an array which you can return from your method.

    I hope this gives you some ideas... let me know if you have any trouble getting the code going.

    Thanks!

    Comment

    • Rohit Garg
      New Member
      • Jul 2010
      • 8

      #3
      You can use XMLReader Class to read data from XML files and then you can store data in arrays while reading.

      Comment

      • Christian Binder
        Recognized Expert New Member
        • Jan 2008
        • 218

        #4
        Using LinQ you could do it like
        Code:
        int[] arr = XDocument.Load(@"C:\xxx.xml").Root.Elements("number").Select(element => int.Parse(element.Value)).ToArray();
        But you'd need to have a root-element (as Gary suggested "array") otherwise XDocument.Load would fail.

        Comment

        Working...