podeig
podeig

Reputation: 2741

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.

Upvotes: 0

Views: 348

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

Your error means that some of div elements do not have id attribute. Thus s.Attribute("id") returns null. Trying to get it's value throws exception. If you will cast attribute to string instead of trying to access it's Value, you will not get error (null will be returned if attribute was not found):

xDoc.Descendants("div")
    .Where(d => (string)d.Attribute("id") == "item" + item)
    .Remove();

Also thus you are dealing with HTML I suggest you to use appropriate tool - HtmlAgilityPack. Removing your div nodes will look like:

HtmlDocument doc = new HtmlDocument();
doc.Load(path_to_file);
foreach (var div in doc.DocumentNode.SelectNodes("//div[@id='item456']"))
    div.Remove();

Upvotes: 1

Andrei V
Andrei V

Reputation: 7508

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

Upvotes: 2

Related Questions