Search code examples
c#xmlparsingxmlreader

C# XmlReader - shorter function


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.


Solution

  • 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"));
    }