C# 使用Linq按属性而不是按元素查询XML?

C# 使用Linq按属性而不是按元素查询XML?,c#,xml,asp.net-mvc,linq,C#,Xml,Asp.net Mvc,Linq,我目前正试图从以下XML中删除记录: <?xml version="1.0" encoding="utf-8"?> <Photos> <Photo UID="7e74a528a5324feb8ed3d7902c8b6a42"> <Date>2014-08-22T10:22:00.761873+01:00</Date> <File>7e74a528a5324feb8ed3d7902c8b6a42.jpg&l

我目前正试图从以下XML中删除记录:

<?xml version="1.0" encoding="utf-8"?>
<Photos>
  <Photo UID="7e74a528a5324feb8ed3d7902c8b6a42">
    <Date>2014-08-22T10:22:00.761873+01:00</Date>
    <File>7e74a528a5324feb8ed3d7902c8b6a42.jpg</File>
    <CrimeRef>CR999999/99</CrimeRef>
  </Photo>
  <Photo UID="70c4b3bb2cc54780b49cf10228f472da">
    <Date>2014-08-22T10:49:41.737873+01:00</Date>
    <File>70c4b3bb2cc54780b49cf10228f472da.jpg</File>
    <CrimeRef>CR999999/99</CrimeRef>
  </Photo>
</Photos>
但是,我刚刚开始在Photo元素上填充UID来解决路由问题,所以我想现在按UID值删除文件

我曾尝试循环遍历“Photo”子体,但不幸的是,它只是跳过了与UID匹配的元素(因为,出于某种原因,它不匹配)

根据调试信息,它应该匹配:


欢迎您提供任何建议,谢谢。

您只是忘了检查属性值。 如果您添加
.Value
这将修复它

public void Delete(string ID)
{
    XDocument xml = XDocument.Load(xmlPath);

    xml.Descendants("Photo")
            .Where(e => e.Attribute("UID") != null && (string)e.Attribute("UID").Value == ID)
            .Remove();
}
使用值属性:

doc.Descendants().Where(e => (string) e.Attribute("UID").Value == ID).Remove();

.Where(e=>(string)e.Attribute(“UID”).Value==ID)
非常感谢James,我刚刚测试了这个,但是当第一个元素不匹配时,我得到一个
系统.NullReferenceException
错误。更新为包含空检查您是明星,非常感谢-仔细想想,如果我从一开始就像我应该做的那样填充UID,这就不会是一个问题。唉。再次感谢:)
public void Delete(string ID)
{
    XDocument xml = XDocument.Load(xmlPath);

    xml.Descendants("Photo")
            .Where(e => e.Attribute("UID") != null && (string)e.Attribute("UID").Value == ID)
            .Remove();
}
doc.Descendants().Where(e => (string) e.Attribute("UID").Value == ID).Remove();