-1

My XML looks like this:

<data>
  <location ....>
      <stores>
         <store ....></store>
         <store ... ></store>
      </stores>
  </location>
</data>

I want to loop through all the location elements, and then loop through all the stores.

I also want access to the attributes of both location and store elements.

I have loaded the xml document:

var doc = new XmlDocument();
doc.LoadXml(myXmlAsString);
cool breeze
  • 4,461
  • 5
  • 38
  • 67

3 Answers3

1

Let's say this is your sample XML

<data>
  <location sample="something">
      <stores>
         <store atrb="1">store1</store>
         <store atrb="2">store2</store>
      </stores>
  </location>
  <location>
      <stores>....</stores>
  </location>
</data>

Then using XDocument of System.Xml.Linq, you access all the locations, stores and their attributes like this

var xmlString = File.ReadAllText(@"C:\YourDirectory\YourFile.xml");
XDocument geneva = XDocument.Parse(xmlString);

var locations = geneva.Descendants("location");
foreach (var location in locations)
{
    var sampleAttribute = location.Attribute("sample").Value;
    var stores = location.Descendants("store");
    foreach (var store in stores)
    {
        var value = store.Value;
        var atrbValue = store.Attribute("atrb").Value;
    }
}
Arghya C
  • 9,805
  • 2
  • 47
  • 66
0

If you dont want to use XmlSerializer to get the typed data you can get nodes by criteria with SelectSingleNode or SelectNodes methods. This will give you ability to iterate through location elemets. I would suggest creating classes to deserialize to because its easier to work with.

Matija Gobec
  • 850
  • 6
  • 12
0

Loop through locations:

XmlNodeList xnList = doc.SelectNodes("/data/location");
            foreach(XmlNode node in xnList)
            {
                  //your code goes here..
            }

Loop through all stores:

XmlNodeList xnList = doc.SelectNodes("/data/location/stores");
            foreach(XmlNode node in xnList)
            {
                    //your code here..
            }
null1941
  • 972
  • 8
  • 20