c# - Cant delete XmlElement using Linq query -



c# - Cant delete XmlElement using Linq query -

i have basic linq query able delete 1 node xml file.but when ı run code getting exception below.

sequence contains no elements

then have used firstordefault() instead first() ( mentioned before posts) , time exection message turned this

object reference not set instance of object.

this code

protected void page_load(object sender, eventargs e) { xdocument doc = xdocument.load(server.mappath("kitaplar.xml")); var todelete = (from info in doc.elements("kitap") data.attribute("id").value == "1" select data).firstordefault(); todelete.remove(); doc.save(server.mappath("kitaplar.xml")); }

and xmlfile

<?xml version="1.0" encoding="utf-8"?> <kitaplar> <kitap id="1"> <kitapadi>asasa</kitapadi> <yazar>sasas</yazar> <sayfa>22</sayfa> </kitap> <kitap id="2"> <kitapadi>jhjh</kitapadi> <yazar>kjkj</yazar> <sayfa>33</sayfa> </kitap> <kitap id="3"> <kitapadi>lkjhg</kitapadi> <yazar>gffd</yazar> <sayfa>988</sayfa> </kitap> <kitap id="4"> <kitapadi>lkjhg</kitapadi> <yazar>gffd</yazar> <sayfa>988</sayfa> </kitap> </kitaplar>

everyting looks ok me.what doing wrong ?

i took liberty of writing method takes file, element , id; removes element accordingly.

private bool deleterowwithid(string filename, string element, string id) { xdocument doc = xdocument.load(filename); if (doc.root == null) homecoming false; xelement toremove = doc.root.elements(element).where(e => e.attribute("id").value == id).firstordefault(); if (toremove == null) homecoming false; toremove.remove(); doc.save(filename); homecoming true; }

above method loads xmldocument in xdocument (which allows linq xml). checks if root isn't empty, finds element specified.

it checks if element exists; removes element document, , save made removal.

last, returns true indicate element has been removed.

if want element , stick method, utilize following:

xelement toremove = doc.root.elements("kitap").where(e => e.attribute("id").value == "1").firstordefault();

c# linq linq-to-xml

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -