Nick
Nick

Reputation: 3965

Using Linq to query XML by attribute rather than by element?

I currently have the following XML which I'm trying to remove a record from:

<?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>

Previously, I was removing records by search for the file name using the following code which worked fine:

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

    xml.Descendants("Photos")
            .Where(e => (string)e.Attribute("File") == ID)
            .Remove();
}

However, I've just started populating the UID on the Photo element to get around routing issues, so I'd like to remove the files now by the UID value.

I've tried looping through the "Photo" descendants but unfortunately it's just skipping over the element that matches the UID (because, for some reason it isn't matching)

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

    xml.Descendants("Photo")
            .Where(e => (string)e.Attribute("UID") == ID)
            .Remove();
}

From the debug information, it should match:

enter image description here

Any suggestions would be very welcome, thank you.

Upvotes: 0

Views: 61

Answers (2)

mashet
mashet

Reputation: 876

Use Value property:

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

Upvotes: 0

Lotok
Lotok

Reputation: 4607

You just forgot to check for the attribute value. If you add .Value this will fix it.

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

Upvotes: 1

Related Questions