Friday, 15 March 2013

How get parent element attribute and child value from XML in java? -



How get parent element attribute and child value from XML in java? -

i have xml file, example:

<parent value="first"> <child>bill</child> </parent>

i want @ output: value=first,child=bill means need attribute parrent element , value kid element.

i tried this:

list<str> obj = new arraylist<str>(); nodelist nlist = doc.getelementsbytagname("parent"); (int = 0; < nlist.getlength(); ++i) { element attrelement = (element) nlist.item(i); namednodemap map = attrelement.getattributes(); (int j = 0; j < map.getlength(); j++) { node attribute = map.item(j); node enode = nlist.item(j); element name = (element) enode; obj.add(new str(attribute.getnodevalue(), name.getelementsbytagname("child").item(0).gettextcontent())); } }

in result have str "null" values.

use

list<string> obj = new arraylist<string>(); nodelist nlist = doc.getelementsbytagname("parent"); (int = 0; < nlist.getlength(); ++i) { namednodemap map = nlist.item(i).getattributes(); (int j = 0; j < map.getlength(); j++) { node attribute = map.item(j); node enode = nlist.item(i); // utilize value here issue. element name = (element) enode; obj.add(new string("value = "+attribute.getnodevalue() + ",child=" + name.getelementsbytagname("child").item(0).gettextcontent())); } }

add 1 outer element,it works fine multiple tags

<xml><parent value=first> <child>bill</child></parent> <parent value=second> <child>steve</child></parent></xml>

java xml xml-parsing

No comments:

Post a Comment