2010-12-16 39 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

相關問題