2010-12-16 47 views
1

好的。所以,与Windows Phone 7的应用程序,说我有下面的XML文件从XML文档加载数据在Windows Phone上使用XDocument时引发NullReferenceException 7

<Objects> 
    <Object Property1=”Value1” Property2=”Value2”> 
     <Property3>Value3</Property3> 
    </Object> 
    <Object Property1=”Value1” Property2=”Value2”> 
     <Property3>Value3</Property3> 
    </Object> 
</Objects> 

而且我有下面的类定义

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 
    } 
} 

,然后我用下面的代码从XML加载数据文件并返回一个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>(); 

为什么这会返回一个NullReferenceException?我猜这是我的linq查询不是很正确,因为该文件正在加载XDocument.Load调用罚款。

任何帮助将是太棒了!

克里斯

回答

4

的XML结构,你目前它,你需要一个LINQ查询是这样的:

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 
    }; 

就像约翰说,o.Attribute( “的attributeName”)或o.Element( “的ElementName”)将在元素或属性不存在时抛出NullReferenceException。

+0

+1属性1,属性2是看你的xml。在我可以回复之前分神,这应该排除你的问题。 – 2010-12-17 01:57:00

0
Property1 = o.Element("Property1").Value 

将抛出时,针对 “o” 不具有 “Property1” 元素运行一个NullReferenceException!该方法将返回null

相关问题