c# - Selecting a child node having specific value -


i want check if "< city>" node 'having specific value (say pathankot )' exist in xml file under particular "< user id="any"> having specific id", before inserting new city node xml.

< users>       < user id="4/28/2015 11:29:44 pm">            <city>fazilka</city>            <city>pathankot </city>            <city>jalandher</city>            <city>amritsar</city>       </user>  </users>  

in order insert using following c# code

 xdocument xmldocument = xdocument.load(@"c:\users\ajax\documents\userselectedcity.xml");         string usrcookieid = request.cookies["cookieid"].value; xmldocument.element("users")             .elements("user") .single(x => (string)x.attribute("id") == usrcookieid)              //incomplete because same named cities can entered more once               //need make delete function             .add(             new xelement("city", drpwheretogo.selectedvalue)); 

my questions:

  • how can check weather < city> node having specific value pathankot exist in xml file before inserting new city node.
  • i using absolute path in" xdocument xmldocument =
    xdocument.load(@"c:\users\ajax\documents\visual studio
    2012\websites\punjabtourism.com\userselectedcity.xml");"
    not allow me move files new folder without changing
    path not desirable. if use relative path the
    error occures "access denied";

try this:-

first load xml file xdocument object specifying physical path xml file present. once have object take first node matching condition (please note using first instead of single cz may have multiple nodes same matching condition, please see difference between single & first)

xdocument xmldocument = xdocument.load(@"yourphysicalpath"); xmldocument.descendants("user").first(x => (string)x.attribute("id") == "1"                    && x.elements("city").any(z => z.value.trim() == "pathankot"))                  .add(new xelement("city", drpwheretogo.selectedvalue)); xmldocument.save("yourphysicalpath"); 

finally add required city node retrieved query , save xdocument object.

update:

if want check first if criteria fulfills use any this:-

bool iscitypresent = xdoc.descendants("user").any(x => (string)x.attribute("id") == "1"                   && x.elements("city").any(z => z.value.trim() == "pathankot")); 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -