android - Getting error in DOM Parser -
private string getnodevalue(element e) { string str = ""; node node = e.getfirstchild(); if (node instanceof characterdata) { characterdata cd = (characterdata) node; str += cd.getdata(); } system.out.println("string ="+ str); return str; } i using code parse xml using dom
edit!
<?xml version="1.0" encoding="iso-8859-1"?> <root status="1"> <reminder type= "timer" id="861"> <user fromid="48" toid="48" fromemail="xyz@xyz.com">dharmendra patel</user> <title>10:00 coffy?</title> <desc>let's go coffy</desc> <date>13/03/2011 09:22:00</date> <repeat>mo</repeat> <todo><category name=""> <item></item> </category> </todo> </reminder> </root> this xml response , using code
nodelist nldesc = eluser.getelementsbytagname("desc"); element eldesc = (element) nldesc.item(0); string taskdesc = getnodevalue(eldesc); if node value contains string "let's go coeffy" gives me string "lets go coeffy" problem ? please me..
you can use element.gettextcontent() getting element text. note, method can accesed in api level 8 , higher.
in api level less 8 can use getnodevalue method. succeed if node of type text_node
edit
try { document doc = documentbuilderfactory .newinstance() .newdocumentbuilder().parse( new stringbufferinputstream("<desc>let's go coffey </desc>")); nodelist list = doc.getelementsbytagname("desc"); log.d("mainactivity", list.item(0).getfirstchild().getnodevalue()); } catch (parserconfigurationexception e) { // ignore } catch (ioexception e) { // ignore } catch (saxexception e) { // ignore } the following code works fine. after executed i've got @ logcat:
04-12 21:20:42.766: debug/mainactivity(26843): let's go coffey edit 2:
to deal #&... entities use html.fromhtml(string) method on encoded string , tostring() on result.
log.d("mainactivity", html.fromhtml( list.item(0).getfirstchild().getnodevalue() ).tostring()); edit 3
here complete solution case.
string data = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?> <root status=\"1\"> <reminder type= \"timer\" id=\"861\"> <user fromid=\"48\" toid=\"48\" fromemail=\"xyz@xyz.com\">dharmendra patel</user> <title>10:00 coffy?</title> <desc>let's go coffy</desc> <date>13/03/2011 09:22:00</date> <repeat>mo</repeat> <todo><category name=\"\"> <item></item> </category> </todo> </reminder> </root>"; try { document doc = documentbuilderfactory .newinstance() .newdocumentbuilder().parse( new stringbufferinputstream(data)); nodelist list = doc.getelementsbytagname("desc"); node node = list.item(0); nodelist charnodes = node.getchildnodes(); stringbuilder builder = new stringbuilder(); for(int = 0, l = charnodes.getlength(); < l; i++) { builder.append(html.fromhtml(charnodes.item(i).getnodevalue()).tostring()); } log.d("mainactivity", builder.tostring()); } catch (parserconfigurationexception e) { // ignore } catch (ioexception e) { // ignore } catch (saxexception e) { // ignore }
Comments
Post a Comment