Search code examples
c#xmlxmlreader

How to iterate a xml file with XmlReader class


my xml stored in xml file which look like as below

<?xml version="1.0" encoding="utf-8"?>
<metroStyleManager>
  <Style>Blue</Style>
  <Theme>Dark</Theme>
  <Owner>CSRAssistant.Form1, Text: CSR Assistant</Owner>
  <Site>System.ComponentModel.Container+Site</Site>
  <Container>System.ComponentModel.Container</Container>
</metroStyleManager>

this way i am iterating but some glitch is there

 XmlReader rdr = XmlReader.Create(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\Products.xml");
            while (rdr.Read())
            {
                if (rdr.NodeType == XmlNodeType.Element)
                {
                    string xx1= rdr.LocalName;
                    string xx = rdr.Value;
                }
            }

it is always getting empty string xx = rdr.Value; when element is style then value should be Blue as in the file but i am getting always empty....can u say why?

another requirement is i want to iterate always within <metroStyleManager></metroStyleManager>

can anyone help for the above two points. thanks


Solution

  • Blue is the value of Text node, not of Element node. You either need to add another if to get value of text nodes, or you can read inner xml of current element node:

    rdr.MoveToContent();
    
    while (rdr.Read())
    {
        if (rdr.NodeType == XmlNodeType.Element)
        {                    
            string name = rdr.LocalName;
            string value = rdr.ReadInnerXml();
        }
    }
    

    You can also use Linq to Xml to get names and values of root children:

    var xdoc = XDocument.Load(path_to_xml);
    var query = from e in xdoc.Root.Elements()
                select new {
                   e.Name.LocalName,
                   Value = (string)e
                };