Reputation: 1427
I am trying to parse an XML file, using a method that I copied from elsewhere and works fine with XML that has only elements with no attributes, but fails with attributes. Sample XML look like this:
<name>tester</name>
<trkseg>
<trkpt lat="50.26241" lon="-5.05005">
<ele>6.9</ele>
</trkpt>
<trkpt lat="50.26242" lon="-5.05012">
<ele>6.9</ele>
</trkpt>
....
and my code snippet looks like this:
IEnumerable<Track> tracks =
from trackElement in root.Descendants(ns1 + "trkseg")
select new Track
{
TrackPoints =
(from trackPointElement in trackElement.Descendants(ns1 + "trkpt")
select new TrackPoint
{
pos = new Position
{
LatitudeDegrees = Convert.ToDouble(trackPointElement.Attribute(ns1 + "lat").Value),
LongitudeDegrees = Convert.ToDouble(trackPointElement.Attribute(ns1 + "lon").Value),
},
AltitudeMeters = trackPointElement.Element(ns1 + "ele") != null
? Convert.ToDouble(trackPointElement.Element(ns1 + "ele").Value) : 0.0,
}).ToList()
};
but I am getting a null exception on the attribute ("System.Xml.Linq.XElement.Attribute(...) returned null"). The 'ele' element, and the 'name' element are correctly found (if I just create a dummy position of (0,0) instead, the whole file parses correctly). How should I code the attribute value?
Upvotes: 1
Views: 101
Reputation: 116533
Unlike elements, XML attributes are never in a namespace by default, so replace trackPointElement.Attribute(ns1 + "lat")
with trackPointElement.Attribute("lat")
:
pos = new Position
{
LatitudeDegrees = XmlConvert.ToDouble(trackPointElement.Attribute("lat").Value),
LongitudeDegrees = XmlConvert.ToDouble(trackPointElement.Attribute("lon").Value),
}
For confirmation see Namespaces in XML 1.0 (Third Edition): 6.2 Namespace Defaulting:
The namespace name for an unprefixed attribute name always has no value.
I also recommend replacing Convert.ToDouble()
with XmlConvert.ToDouble()
to ensure that the XML is parsed consistently across locales. Or use the explicit conversion to double
as mentioned in comments by juharr which does the same thing.
Upvotes: 1