この種の作業には JDOM2 をお勧めします。あなたの提案は次のように実現できます。
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
public void transformXmlFile(File oldFile, File newFile) throws Exception
{
Document oldDocument = new SAXBuilder().build(oldFile);
Document newDocument = new Document(transformElement(oldDocument.getRootElement()));
List<Element> children = new LinkedList<Element>();
for (Element oldElement : oldDocument.getRootElement().getChildren())
children.add(transformElement(oldElement));
for (Element oldElement : sortElements(children))
newDocument.getRootElement().addContent(oldElement);
XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
serializer.output(newDocument, new FileOutputStream(newFile));
}
private Element transformElement(Element oldElement)
{
Element newElement = new Element(oldElement.getName(), oldElement.getNamespace());
List<Attribute> attributes = new LinkedList<Attribute>();
for (Attribute a: oldElement.getAttributes())
attributes.add(a.clone());
for (Attribute a: sortAttributes(attributes))
newElement.getAttributes().add(a);
return newElement;
}
private List<Attribute> sortAttributes(List<Attribute> attributes)
{
Collections.sort(attributes, new Comparator<Attribute>()
{
@Override
public int compare(Attribute a1, Attribute a2)
{
return a1.getName().compareTo(a2.getName());
}
});
return attributes;
}
private List<Element> sortElements(List<Element> elements)
{
Collections.sort(elements, new Comparator<Element>()
{
@Override
public int compare(Element e1, Element e2)
{
return e1.getName().compareTo(e2.getName());
}
});
return elements;
}