xml creation using java -
i want iterate on xml given below:
<annotation> <properties> <propertyvalue propertyname="field_label">label.modelseriescd</propertyvalue> <propertyvalue propertyname="containertype">conditioncontainer</propertyvalue> </properties> </annotation>
i trying these codes: 1)
while(currentnode.haschildnodes()){ system.out.println(currentnode.getnextsibling()); currentnode=currentnode.getnextsibling(); }
2)
for (int x = 0; x < childnode.getlength(); x++) { node current = childnode.item(x); if (node.element_node == current.getnodetype()) { string cn = current.getnodename(); system.out.print(cn +" = "); string cv = current.getnodevalue(); system.out.print(cv+" : "); string ct = current.gettextcontent(); system.out.println(ct); } }
output:
[shape: null] shapetype = null : h2 annotation = null : label.modelseriescd conditioncontainer
i want output tag names , tag values i.e. should display like: properties propertyvalue propertyname "field_label" value label.modelseriescd means want output tags ,attribute name, attribute values , text values. can write in xml
the method below recurse on xml tree, printing requested info:
public static void printnodetree(node n) { // print xml element name: system.out.println("elem: " + n.getnodename()); // print xml element attributes: namednodemap attrs = n.getattributes(); if (attrs != null) { (int = 0; < attrs.getlength(); i++ ) { node attr = attrs.item(i); system.out.println("attr: " + attr.getnodename() + " = " + attr.getnodevalue()); } } nodelist nodelist = n.getchildnodes(); // print xml element text value (int = 0; < nodelist.getlength(); i++) { node currentnode = nodelist.item(i); if (currentnode.getnodetype() == node.text_node) { string text = currentnode.getnodevalue(); if (text != null && text.matches("\\s+")) { system.out.println("text: " + text); } } } // recurse on child elements (int = 0; < nodelist.getlength(); i++) { node currentnode = nodelist.item(i); if (currentnode.getnodetype() == node.element_node) { printnodetree(currentnode); } } }
you can initiate traversal document root:
document doc = ... printnode(doc.getdocumentelement());
output given input:
elem: annotation elem: properties elem: propertyvalue attr: propertyname = field_label text: label.modelseriescd elem: propertyvalue attr: propertyname = containertype text: conditioncontainer
Comments
Post a Comment