Search code examples
c#htmlxmllinqxelement

Can't remove an element in XML


I have XElement xDoc =

<div id="item123">
    <div id="item456">
        <h3 id="1483538342">
           <span>Dessuten møtte</span> 
        </h3>
        <p>Test!</p> 
    </div>
</div>

When I try to remove en item with id = "item456" I get an error

System.NullReferenceException: Object reference not set to an instance of an object.

var item = "456";
xDoc.Descendants("div").Where(s => s.Attribute("id").Value == "item" + item).Remove();

I can't understand what is wrong here.


Solution

  • You need to check if the current element (inside the where iteration) has an id attribute, otherwise you will access a null object and get an exception.

    var item = "456";
    xDoc.Descendants("div").Where(s => s.Attribute("id") != null && s.Attribute("id").Value == "item" + item).Remove();