0

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.

1
  • 1
    .Where(e => (string)e.Attribute("UID").Value == ID) Commented Aug 22, 2014 at 10:23

2 Answers 2

1

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much James, I've just tested this, but when the first element doesn't match I get a System.NullReferenceException error.
Updated to include the null check
You're a star, thank you so much - thinking about it this wouldn't have been an issue if I'd populated the UID from the start like I should have done. Sigh. Thanks again :)
0

Use Value property:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.