Question

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

Was it helpful?

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
            };

OTHER TIPS

You can use the XmlDocument class for this.

XmlDocument doc = new XmlDocument.Load(filename);
foreach (XmlNode node in doc.ChildNodes)
{
    if (node.ElementName == "metroStyleManager")
    {
        foreach (XmlNode subNode in node.ChildNodes)
        {
            string key = subNode.LocalName; // Style, Theme, etc.
            string value = subNode.Value; // Blue, Dark, etc.
        }
    }
    else
    {
        ...
    }
}

you can user XDocument xDoc = XDocument.Load(strFilePath) to load XML file.

then you can use

foreach (XElement xeNode in xDoc.Element("metroStyleManager").Elements())
{
    //Check if node exist
    if (!xeNode.Elements("Style").Any()

    //If yes then
    xeNode.Value
}

Hope it Helps...

BTW, its from System.XML.Linq.XDocument

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top