0

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

3 Answers 3

1

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
            };
Sign up to request clarification or add additional context in comments.

Comments

0

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
    {
        ...
    }
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.