Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用XDocument确定是否存在具有特定属性的元素?_C#_Asp.net_Xml_Linq_Linq To Xml - Fatal编程技术网

C# 使用XDocument确定是否存在具有特定属性的元素?

C# 使用XDocument确定是否存在具有特定属性的元素?,c#,asp.net,xml,linq,linq-to-xml,C#,Asp.net,Xml,Linq,Linq To Xml,我正尝试使用LINQ和XDocument根据以下特定条件从XML文档中删除条目: xml.Descendants("Photos").Where(e => e.Attribute("File").Value.Equals(ID)).Remove(); 但是,在没有找到条目的情况下,它会抛出NullReferenceException错误。我试图获得所有匹配元素的计数,但不幸的是,我得到了相同的错误: public void Delete(string ID) { XDocumen

我正尝试使用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();
问题在于:

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();

不要使用
属性。使用显式强制转换并使用
=

.Where(e => (string) e.Attribute("File") == ID)

如果未找到
属性,则不会引发异常,它将返回
null

不要使用
属性。使用显式强制转换并使用
=

.Where(e => (string) e.Attribute("File") == ID)

如果未找到
属性
,它将不会引发异常,相反,它将返回
null

这是绝对完美的,它也适用于
.Remove()
函数,这有助于简化我的代码。非常感谢。这绝对是完美的,而且它也适用于
.Remove()
函数,这有助于简化我的代码。非常感谢。