您可以創建一個可以輕鬆重複使用的擴展方法。把它放在一個靜態類
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 ?? "";
感謝,如果我們的代碼將返回null,如果不存在,返回值如果在場我是否正確 – GowthamanSS