Search code examples
c#xml.net-4.5xelement

Foreach loop will not read XML


I am trying to read some data from an XML. I am using the same code in another application with an almost identical XML layout which seems to work.. But I cannot get any of the code to run inside the foreach loop with this code:

It seems to read the XML ok if If have a breakpoint and view _xml.Elements

 XElement value in _xml.Elements("effects").Elements("effect")

C#

 XElement _xml = XElement.Load("Effects.xml");
                {
                    foreach (XElement value in _xml.Elements("effects").Elements("effect"))
                    {
                       //will not execute any code in here.
                        DVOXML _item = new DVOXML();
                        _item.Name = value.Element("name").Value;
                        _item.Param = value.Element("params").Value;


                    }
                }

XML:

  <?xml version="1.0" ?>
 <effects>
   <effect>
    <name>effect1</name>
    <params>xmldata</params>
  </effect>
  <effect>
    <name>effect2</name>
    <params>xmldata</params>
  </effect>
</effects>

Solution

  • In your case effects is the root.

    Use this:

    foreach (XElement value in _xml.Elements("effect"))
    {
      .....
    }