3

我想阅读 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>

我也想做属性和缩进!

4

3 回答 3

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>
于 2013-07-06T21:42:11.057 回答
1

您可以使用 XSLT 转换 XML 数据并使用<xsl:sort>

于 2013-07-06T11:14:02.167 回答
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;
}
于 2013-07-06T12:22:53.180 回答