Skip to content

Reading XML Files

May 5, 2011

Since my tasks today entailed reading and writing XML files, I thought I would write a simple XML reader that writes to the console the elements and text values of all the XML files in a directory, here goes: –

string[] xmlFiles = Directory.GetFiles(@”C:XML”, “*.xml”, SearchOption.TopDirectoryOnly);

}if (xmlFiles.Length == 0)

{

    Console.WriteLine(@”No xml file found under C:Conversion directory , please try again”);

    Console.WriteLine(“Press any key to exit.”);

    return;

}

The last portion of code simply writes the XML element names and its values to the console.

foreach (string file in xmlFiles)

{

    XmlTextReader reader = newXmlTextReader(file);

    while (reader.Read())

    {

        switch (reader.NodeType)

        {

            case XmlNodeType.Element: // The node is an element.

                Console.Write(“<“ + reader.Name);

                Console.WriteLine(“>”);

                break;

            case X mlNodeType.Text: //Display the text in each element.

                Console.WriteLine (reader.Value);

                break;

            case X mlNodeType.EndElement: //Display the end of the element.

                Console.Write(“</” + reader.Name);

                Console.WriteLine(“>”);

                break;

            }

        }

        Console.ReadLine();

    }

}

Obviously this is a very simple example, but you can manipulate the name and values, and store them for later use for something, in my case i am interested in the attributes, so you can do a read based on the case element, and use the code: –

reader.GetAttribute(0));

This gets the value of the first attribute of that XML element tag.

Hope that helps.

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: