java - Parsing XML attributes from Complex Empty Elements -
i have xml file in following pattern contains few complex empty elements
(elements no content, attributes).
<items> <item id="0" name="a" /> <item id="1" name="b" /> </items>
i'm @ lose parse attributes them. have done far :
documentbuilderfactory factory = documentbuilderfactory.newinstance(); documentbuilder builder = factory.newdocumentbuilder(); document document = builder.parse(inputstream); element itemselement = document.getdocumentelement(); if (itemselement.gettagname().equals(tag_items)) { nodelist nodelist = itemselement.getchildnodes(); (int = 0; < nodelist.getlength(); i++) { // process each item node node node = nodelist.item(i); if (node.getnodetype() == node.text_node) { // right way? text text = (text) node; // stuff attributes } } }
i cannot cast these text
nodes element
nodes , attributes, cannot attributes node using getattributes
- npe @ namednodemap attributes.getlength()
, cannot cast text
, attributes. how can parse attributes?
you not interested in text context of nodes inside of items
in attributes of nodes item
. proceed follow:
//process each item node node node = nodelist.item(i); if (node.getnodename().equals("item")) { namednodemap attributes = node.getattributes(); system.out.printf("id=%s, name=%s%n", attributes.getnameditem("id").gettextcontent(), attributes.getnameditem("name").gettextcontent()); }
this print:
id=0, name=a id=1, name=b
Comments
Post a Comment