1 | |
package com.aurea.maven.plugins.sonic.utils.xmlsorter; |
2 | |
|
3 | |
import java.io.File; |
4 | |
import java.io.FileWriter; |
5 | |
import java.io.IOException; |
6 | |
import java.util.ArrayList; |
7 | |
import java.util.Collections; |
8 | |
import java.util.Comparator; |
9 | |
import java.util.List; |
10 | |
|
11 | |
import org.codehaus.plexus.util.xml.XmlStreamReader; |
12 | |
import org.codehaus.plexus.util.xml.Xpp3Dom; |
13 | |
import org.codehaus.plexus.util.xml.Xpp3DomBuilder; |
14 | |
import org.codehaus.plexus.util.xml.Xpp3DomWriter; |
15 | |
import org.codehaus.plexus.util.xml.pull.XmlPullParserException; |
16 | |
import org.w3c.dom.Text; |
17 | |
|
18 | |
|
19 | 0 | public class XMLSort { |
20 | |
|
21 | |
|
22 | |
public static void sortXMLFile(final File file) throws IOException { |
23 | |
|
24 | |
try { |
25 | 0 | XmlStreamReader inputReader = new XmlStreamReader(file); |
26 | |
|
27 | |
Xpp3Dom fileDom; |
28 | 0 | fileDom = Xpp3DomBuilder.build(inputReader); |
29 | 0 | XMLSort.sortChildNodes(fileDom, 2, new AttributeNameComparator()); |
30 | |
|
31 | 0 | FileWriter writer = new FileWriter(file); |
32 | 0 | Xpp3DomWriter.write(writer, fileDom); |
33 | 0 | writer.close(); |
34 | 0 | } catch (XmlPullParserException e) { |
35 | 0 | throw new IOException("Could not parse XML file " + file.getAbsolutePath()); |
36 | 0 | } |
37 | 0 | } |
38 | |
|
39 | |
|
40 | |
|
41 | |
|
42 | |
|
43 | |
|
44 | |
|
45 | |
|
46 | |
|
47 | |
|
48 | |
|
49 | |
|
50 | |
public static void sortChildNodes(final Xpp3Dom dom, final int depth, final Comparator<Xpp3Dom> comparator) { |
51 | |
|
52 | 0 | Comparator<Xpp3Dom> comp = (comparator != null) ? comparator : new DefaultNodeNameComparator(); |
53 | 0 | List<Xpp3Dom> xpp3Doms = new ArrayList<Xpp3Dom>(); |
54 | 0 | for (int i = 0; i < dom.getChildCount(); i++) { |
55 | 0 | Xpp3Dom child = dom.getChild(i); |
56 | 0 | if (depth > 1) { |
57 | 0 | sortChildNodes(child, depth - 1, comparator); |
58 | |
} |
59 | |
|
60 | 0 | if ((!(child instanceof Text)) || (child instanceof Text && ((Text) child).getTextContent().trim().length() > 1)) { |
61 | 0 | xpp3Doms.add(child); |
62 | |
} |
63 | |
} |
64 | |
|
65 | 0 | Collections.sort(xpp3Doms, comp); |
66 | 0 | while (dom.getChildCount() > 0) { |
67 | 0 | dom.removeChild(0); |
68 | |
} |
69 | |
|
70 | 0 | for (Xpp3Dom xpp3Dom : xpp3Doms) { |
71 | 0 | dom.addChild(xpp3Dom); |
72 | 0 | } |
73 | |
|
74 | 0 | } |
75 | |
|
76 | |
} |
77 | |
|
78 | 0 | class DefaultNodeNameComparator implements Comparator<Xpp3Dom> { |
79 | |
|
80 | |
|
81 | |
public int compare(final Xpp3Dom arg0, final Xpp3Dom arg1) { |
82 | |
|
83 | 0 | return arg0.getName().compareTo(arg1.getName()); |
84 | |
} |
85 | |
|
86 | |
} |