我想阅读XML文档,以确定的顺序重新排序节点和属性,例如:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>foobar</artifactId>
<version>0.0.1-SNAPSHOT</version>
</project>
变为:
<project>
<artifactId>foobar</artifactId>
<groupId>com</groupId>
<modelVersion>4.0.0</modelVersion>
<version>0.0.1-SNAPSHOT</version>
</project>
我也想做属性和缩进!
答案 0 :(得分:2)
您的示例没有任何属性,通常您无法控制属性的顺序。但是在XSLT中排序元素很简单:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates>
<xsl:sort select="name()"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
答案 1 :(得分:1)
答案 2 :(得分:0)
我可以为这种工作推荐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;
}