0

With my limited C# programming experience I have been researching how to read in an XML file for the past 4 days with no luck...I need help.

I know there is XMLReader, XDocument and something to do with LINQ that allows you to read in an XML file.

I only have experience of using streamreader so if all else fails I guess I will need to build my own XML reader using that.

In regards to the structure of my XML file it has a one tag that encompassess everything with a series of other tags that contain many child nodes.

Not sure what to do and running out of ideas.

Thanks

svick
  • 236,525
  • 50
  • 385
  • 514
user2230423
  • 69
  • 1
  • 1
  • 5
  • 3
    post your xml file content .. might be easy to crank out a sample code to read your xml content. – scartag Apr 01 '13 at 00:09

5 Answers5

1

The easiest way is to use XDocument. For example:

<myroot>
    <somesub>1</somesub>
    <somesub>2</somesub>
    <somesub>3 <b>- or -</b> 4</somesub>
</myroot>

And then:

string path = @"myfile.xml";
var doc = XDocument.Load(path);

// Get the root node <myroot>
var root = doc.Root;

// Loop through the children and print each one's value:
foreach(var child in root.Elements())
{
    Console.WriteLine(child.Value);
}

Look at the documentation of XElement and XDocument for more ideas and information about the members they have.

Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157
  • What I am planning on doing though is to read the data in the xml, "1,2,3" (using the above example) and then putting those values into either a list, variable or an array. – user2230423 Apr 01 '13 at 00:15
  • Well, I've shown you how to read the values of elements. Now its your job to think of how the strings can be put in a list. That's a whole new question, and not hard to do. – Daniel A.A. Pelsmaeker Apr 01 '13 at 00:22
  • Apologies just played around for a bit I think I am on the right track now thank-you so much! – user2230423 Apr 01 '13 at 00:23
1

You can use the XmlTextReader.

 using (XmlTextReader xmlTextReader = new XmlTextReader("FILE_NAME.xml"))
 {
    while (xmlTextReader.Read())
    {
        switch (xmlTextReader.NodeType)
        {
            // ... Process node types here ex. XmlNodeType.Element
        }
     }
 }

Read more: http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader.aspx

However XmlTextReader does not validate data, so if you want to validate your data use XmlReader: http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx

Bauss
  • 2,767
  • 24
  • 28
1

I recently wrote and published a library that allows querying and displaying nodes, child nodes, and list nodes within an XML file.

using DxF.XML.Finder;

using (MemoryStream xmlStream = new MemoryStream(File.ReadAllBytes("Sample.xml")))
{
    using (XmlReader xmlReader = new XmlReader(xmlStream))
    {
        // Get the total number of 'book' nodes
        int countBook = xmlReader.GetNodeCount("book");

        for (int i = 0; i < countBook; i++)
        {
            // Retrieve the value of specific nodes for each book
            string authorValue = xmlReader.GetNode("book[" + i + "]", "author");
            string titleValue = xmlReader.GetNode("book[" + i + "]", "title");
            string genreValue = xmlReader.GetNode("book[" + i + "]", "genre");
            string priceValue = xmlReader.GetNode("book[" + i + "]", "price");
            string publish_dateValue = xmlReader.GetNode("book[" + i + "]", "publish_date");
            string descriptionValue = xmlReader.GetNode("book[" + i + "]", "description");

            // Print the book details
            Console.WriteLine("----Book " + i + "--------");
            Console.WriteLine("Author: " + authorValue);
            Console.WriteLine("Title: " + titleValue);
            Console.WriteLine("Genre: " + genreValue);
            Console.WriteLine("Price: " + priceValue);
            Console.WriteLine("Publish Date: " + publish_dateValue);
            Console.WriteLine("Description:");
            Console.WriteLine(descriptionValue);
        }
    }
}

https://github.com/ksomaz/DxF.XML

starball
  • 20,030
  • 7
  • 43
  • 238
ksomaz
  • 11
  • 3
0

All of these classes for reading and parsing XML serve different purposes.

Using XDocument (the LINQ flavour) will result in a significantly more readable piece of code but will consume more memory than XmlTextReader.

If you're processing large files use the XmlReader class.

XmlReader example on MSDN

XDocument examples on dotnetcurry

I have personally never liked the XmlDocument class because of the verbose code if forces me to write. That's just me.

Razor
  • 17,271
  • 25
  • 91
  • 138
-1

Here is a sample for your need. you can loop through the XML file with this easiest way.

XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load("sample.xml");

        XmlNodeList name = xmldoc.GetElementsByTagName("name");
        XmlNodeList price = xmldoc.GetElementsByTagName("price");
        XmlNodeList description = xmldoc.GetElementsByTagName("description");
        XmlNodeList calories = xmldoc.GetElementsByTagName("calories");


        for (int i = 0; i < name.Count; i++)
        {
            Console.WriteLine(name[i].InnerText);
            Console.WriteLine("Price: " + price[i].InnerText);
            Console.WriteLine(description[i].InnerText);
            Console.WriteLine("calories: " + calories[i].InnerText);
        }

        Console.ReadKey();
harunu
  • 11
  • 4