문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top