[英]Using XDocument to figure out if an element exists with a specific attribute?
我正在嘗試使用LINQ和XDocument根據特定條件從XML文檔中刪除條目,例如:
xml.Descendants("Photos").Where(e => e.Attribute("File").Value.Equals(ID)).Remove();
但是,在沒有找到條目的情況下,它將引發NullReferenceException錯誤。 我試圖獲取所有匹配元素的計數,但是不幸的是我得到了相同的錯誤:
public void Delete(string ID)
{
XDocument xml = XDocument.Load(xmlPath);
var count = xml.Descendants("Photos").Where(e => e.Attribute("File").Value.Equals(ID)).Count();
if (count >= 1)
{
xml.Descendants("Photos").Where(e => e.Attribute("File").Value.Equals(ID)).Remove();
}
}
但是,這次是在xml...Count()
行上返回錯誤。
關於如何找出匹配元素是否存在任何建議?
謝謝
問題在這里:
e.Attribute("File").Value.Equals(ID)
如果不存在此屬性,則將收到NullReferenceException
。 相反,您可以使用顯式轉換運算符以使您受益:
var count = xml.Descendants("Photos")
.Where(e => (string) e.Attribute("File") == ID)
.Count();
不過,這部分並不是真正需要的,因此直接刪除這些項即可:
xml.Descendants("Photos")
.Where(e => (string) e.Attribute("File") == ID)
.Remove();
不要使用Value
屬性。 使用顯式強制轉換,並使用==
檢查Attribute的值
.Where(e => (string) e.Attribute("File") == ID)
如果找不到Attribute
,則不會拋出異常,而是返回null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.