2012-11-14 45 views
0

讓我們看看下面的XML文檔:獲取使用的XElement與C#.NET null元素

<contact> 
    <name>Hines</name> 
    <phone>206-555-0144</phone> 
    <mobile>425-555-0145</mobile> 
</contact> 

我從中檢索值作爲

var value = parent.Element("name").Value; 

上面的代碼將拋出一個NullReferenceException如果「名稱「不存在,因爲元素將在C#中返回null,但不會在vb.net中返回空值。

所以我的問題是確定什麼時候根節點下面的xml節點丟失,並得到一個空值。

回答

6

您可以創建一個可以輕鬆重複使用的擴展方法。把它放在一個靜態類

public static string ElementValue(this XElement parent, string elementName) 
{ 
    var xel = parent.Element(elementName); 
    return xel == null ? "" : xel.Value; 
} 

現在你可以這樣調用

string result = parent.ElementValue("name"); 

UPDATE

如果返回null而不是一個空字符串時的元素是不存在,這使您有可能區分空元素和缺少元素。

public static string ElementValue(this XElement parent, string elementName) 
{ 
    var xel = parent.Element(elementName); 
    return xel == null ? null : xel.Value; 
} 

 

string result = parent.ElementValue("name"); 
if (result == null) { 
    Console.WriteLine("Element 'name' is missing!"); 
} else { 
    Console.WriteLine("Name = {0}", result); 
} 

編輯

Microsoft使用.NET框架類庫

public static bool TryGetValue(this XElement parent, string elementName, 
                out string value) 
{ 
    var xel = parent.Element(elementName); 
    if (xel == null) { 
     value = null; 
     return false; 
    } 
    value = xel.Value; 
    return true; 
} 
在不同的地方如下模式

可以這樣調用

string result; 
if (parent.TryGetValue("name", out result)) { 
    Console.WriteLine("Name = {0}", result); 
} 

UPDATE

用C#6.0(Visual Studio的2015年),微軟已經推出了零傳播運營商?.簡化了很多東西:

var value = parent.Element("name")?.Value; 

即使未找到該元素,該值也會簡單地設置爲null。

您也可以使用聚結操作??結合起來,如果你想比null返回另一個值:

var value = parent.Element("name")?.Value ?? ""; 
+0

感謝,如果我們的代碼將返回null,如果不存在,返回值如果在場我是否正確 – GowthamanSS

0
var value = parent.Element("name") != null ? parent.Element("name").Value : "" 
+0

感謝我如何能在布爾respesent彷彿真實價值或元素存在或假 – GowthamanSS

4

你的元素簡單地投一些可空類型。的XElement有bunch of overloaded explicit casting operators,這將投元素值所需類型:

string value = (string)parent.Element("name"); 

在這種情況下,如果元素<name>將不會被發現,你會得到字符串值等於nullNullReferenceException將不會被提出

我想如果元素不存在於xml中,那麼null是該元素唯一適當的值。但是,如果你真的需要有空字符串代替,則:

string value = (string)parent.Element("name") ?? ""; 
+1

+1。很優雅的解決方案這些鑄件的唯一標誌就是intellisense沒有透露他們的存在:-( –

+0

@ OlivierJacot-Descombes謝謝!是的,我花了一些時間去習慣元素和屬性的投射,但它真的很方便! –