-1

I've write function that read my XML file. Can i write it more universal and shorter ?

My function:

XmlTextReader reader = new XmlTextReader ("../../database.xml");
    reader.ReadStartElement("eshop");
    while (reader.Read ()) {
        if (reader.IsStartElement ()) {

            reader.ReadStartElement("item");
            reader.ReadStartElement ("id");
            string elem = reader.ReadString ();
            reader.ReadEndElement ();
            reader.ReadStartElement ("name");
            string name = reader.ReadString ();
            reader.ReadEndElement ();
            reader.ReadStartElement ("cost");
            string cost = reader.ReadString ();
            reader.ReadEndElement ();

            Console.WriteLine (elem + " - name  : " + name + " - cost: " + cost);
        }

    }

Example XML:

<?xml version="1.0" encoding="UTF-8" ?>
<eshop>
    <item>
        <id>1</id>
        <name>some product 1</name>
        <cost>89.90</cost>
    </item>
    <item>
        <id>2</id>
        <name>some product 2</name>
        <cost>95.00</cost>
    </item>
    <item>
        <id>3</id>
        <name>some product 3</name>
        <cost>12.00</cost>
    </item>
</eshop>

I don't know how to make this function smaller if i will add new elements to . Now i must add to function this if i want to upgrade my xml file to other elements:

    reader.ReadStartElement ("secondelement");
    string secondelement = reader.ReadString ();
    reader.ReadEndElement ();

Please help. Thank You.

Gregory
  • 11
  • 5
  • 5
    This question appears to be off-topic because it is about refactoring a working code sample. Consider posting on Code Review. – Servy Jan 08 '14 at 18:29

3 Answers3

1

The easiest way to read XML is not to use XmlReader, but to use LINQ to XML (using System.Xml.Linq):

var d = XDocument.Load("../../database.xml");

foreach (var e in d.Root.Elements("item"))
{
    Console.WriteLine(
        (string)e.Element("id") + 
         " - name  : " + (string)e.Element("name") +
         " - cost: " + (string)e.Element("cost"));
}
Mike Strobel
  • 25,075
  • 57
  • 69
0

Take a look at XDocument class:

http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v=vs.110).aspx

You should be able then to use LINQ to read specific elements/attributes.

Similar question:

LINQ to read XML

Community
  • 1
  • 1
Floremin
  • 3,969
  • 15
  • 20
0

Yes, you can use LINQ to XML:

XDocument xDoc = XDocument.Load("../../database.xml");

foreach(var item in xDoc.Descendants("item"))
{
   string id= (string)item.Element("id");
   string name= (string)item.Element("name");
   string cost= (string)item.Element("cost");
   Console.WriteLine("{0} name - {1} - cost {2}",id,name,cost);
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • This is awesome - like in PHP - more readable and easy to remember. Thank You and thanks to Mike for help. Now its time to study LINQ :-) – Gregory Jan 08 '14 at 19:11