Loading data from XML Document throwing a NullReferenceException when using XDocument on Windows Phone 7
Ok. So with a Windows Phone 7 app, say I have the following XML file
<Objects>
<Object Property1=”Value1” Pro开发者_如何学编程perty2=”Value2”>
<Property3>Value3</Property3>
</Object>
<Object Property1=”Value1” Property2=”Value2”>
<Property3>Value3</Property3>
</Object>
</Objects>
And I have the following class definition
public class myObject
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
public myObject (string _property1, string _property2, string _property3)
{
this.Property1 = _property1
this.Property1 = _property1
this.Property1 = _property1
}
}
and I then use the following code to load the data from the XML file and return a list of myObjects:-
var xdoc = XDocument.Load("myXMLFile.xml");
var result = from o in xdoc.Document.Descendants("Object")
select new myObject
{
Property1 = o.Element("Property1").Value,
Property2 = o.Element("Property2").Value,
Property3 = o.Element("Property3").Value,
};
return result.ToList<myObject>();
Why is this returning a NullReferenceException? I'm guessing it is my linq query not being quite right as the file is being loaded just fine with the XDocument.Load call.
any help would be fantastic!
Kris
For the xml structure as you present it, you will need a linq query like this:
var xdoc = XDocument.Load("myXMLFile.xml");
var result = from o in xdoc.Document.Descendants("Object")
select new myObject
{
Property1 = o.Attribute("Property1").Value,
Property2 = o.Attribute("Property2").Value,
Property3 = o.Element("Property3").Value
};
Like John said, o.Attribute("attributeName") or o.Element("elementName") will throw a NullReferenceException when the element or attribute don't exist.
Property1 = o.Element("Property1").Value
will throw a NullReferenceException when run against an "o
" that does not have a "Property1
" element! The Element
method will return null
.
精彩评论