java - Reverse XML Child tags -
what best option reverse lines / tags in xml in java
e.g.
<?xml version="1.0"?> <abc> <xyz1 test1="123" test2="345"> </xyz1> <xyz2 test1="456"> </xyz2> </abc> </xml>
end result
<?xml version="1.0"?> <abc> <xyz2 test1="456"> </xyz2> <xyz1 test2="345" test1="123"> </xyz1> </abc> </xml>
using comparator this:
public int compare(object arg0, object arg1) { if (arg0 instanceof element && arg1 instanceof element) { return ((element) arg0).getattribute("id").compareto( ((element) arg1).getattribute("id")); } else { return ((node) arg0).getnodename().compareto( ((node) arg1).getnodename()); } }
here recursive method can use. puts child nodes in list , sorts them using comparator. don't think can sort attributes, because docs state namednodemaps not maintained in order.
public static void sortchildren(node parent, comparator<node> comparator){ nodelist children = parent.getchildnodes(); if(children.getlength() == 0){ return; } list<node> nodes = new arraylist<node>(); for(int = 0 ; < children.getlength() ; i++){ node n = children.item(i); sortchildren(n, comparator); nodes.add(n); } collections.sort(nodes, collections.reverseorder(comparator)); for(node n : nodes){ parent.appendchild(n); } } public static void main(string[] args) throws exception { document doc = documentbuilderfactory.newinstance().newdocumentbuilder().parse(new file("file.xml")); element root = doc.getdocumentelement(); //sort recursively sortchildren(root, new defaultnodenamecomparator()); //print out (for debugging) outputformat format = new outputformat(doc); format.setlinewidth(65); format.setindenting(true); format.setindent(2); writer out = new stringwriter(); xmlserializer serializer = new xmlserializer(out, format); serializer.serialize(doc); system.out.println(out.tostring()); } class defaultnodenamecomparator implements comparator<node> { public int compare(node arg0, node arg1) { return arg0.getnodename().compareto(arg1.getnodename()); } }
Comments
Post a Comment