In my application I am reading some XML files which are structured like this:
<Locations>
<Location elevation="933.0" id="3072" latitude="56.879" longitude="-3.42" name="Cairnwell" nationalPark="Cairngorms National Park" region="ta" unitaryAuthArea="Perth and Kinross"/>
<Location elevation="4.0" id="3094" latitude="57.698" longitude="-2.121" name="Rosehearty Samos" region="gr" unitaryAuthArea="Aberdeenshire"/>
<Location elevation="35.0" id="3144" latitude="56.326" longitude="-3.729" name="Strathallan" region="ta" unitaryAuthArea="Perth and Kinross"/>
<Location elevation="57.0" id="3166" latitude="55.928" longitude="-3.343" name="Edinburgh/Gogarbank" region="dg" unitaryAuthArea="Edinburgh"/>
<Location elevation="16.0" id="3204" latitude="54.0849" longitude="-4.6321" name="Ronaldsway" region="nw"/>
...
I am reading the name and unitaryAuthArea attributes to put into a string list but not all of the elements have the unitaryAuthArea attribute (like the last one in the xml above) so when I iterate through them it piles up the unitaryAuthArea attributesn without returning "" so they are offset by their name attribute and the all mix up. What I should get if 'Area3' does not exist with its name:
Name1, Area1
Name2, Area2
Name3, Area3 = "Area is not specified"
Name4, Area4
Name5, Area5
What I actually get if 'Area3' is non existent:
Name1, Area1
Name2, Area2
Name3, Area4
Name4, Area5
Name5, [error is thrown]
They all stack up and the name/value pairs don't match anymore. How can I get it so if an attribute doesn't exist then it should return a string like "Not specified'? I have also had this before when reading gusts from another file where only the gust attribute is added if there is a value so I get all the gusts at the top in one block instead of in with its row that it should be. I have tried this but it doesn't work:
List sites = new List();
XmlDocument data = new XmlDocument();
data.Load("http://datapoint.metoffice.gov.uk/public/data/val/wxobs/all/xml/sitelist?key=");
for (int x = 0; x < data.SelectNodes("Locations/Location").Count; x++)
{
string location = "";
string name = data.SelectNodes("Locations/Location/@name")[x].InnerText;
if (data.SelectNodes("Locations/Location/@unitaryAuthArea")[x] == null)
{ location = "NOT AVAILABLE"; }
else { location = data.SelectNodes("Locations/Location/@unitaryAuthArea")[x].InnerText; }
sites.Add(name + ", " + location);
}
siteList.ItemsSource = sites;
I just get "NOT AVAILABLE" on the last item and not the fifth down where the attribute is missing. How can I fix this? Thank you.