如果你只是组装xml的话,我个人不推荐用Document去解析。没必要去创建那些类加你直接用StringBuffer去组装,又方便又可以得到你要的那个顺序在解析的时候你可以用正则,也可以用dom4j之类的开源项目去解析,会很快很多。所以,你要的那个效果可以用StringBuffer组装,更容易得到。

解决方案 »

  1.   


    没看过dom 或者 dom4j 源码,不过想来应该是 hashMap实现的吧,支持kokoBox,如果要按照顺序业,可能只有 stringBuffer了
      

  2.   

    XML的属性是无序的。你那两个XML完全等价。研究这个没有意义。
      

  3.   

    建议使用一些xml反而api, 比如castor, xstream.
    很容易使用, 而且更清晰. 
    object -> xml
      

  4.   

    为什么我的顺序是正确的呢,就是调用setAttribute的顺序。
    代码如下:DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory..newDocumentBuilder();
    Document document = builder.newDocument();
    Element root = document.createElement("root");
    root.setAttribute("name", "aaa");
    root.setAttribute("value", "123");
    document.appendChild(root);
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    if (transformer != null) {
        StringWriter sw = new StringWriter();
        transformer.transform(new DOMSource(node), new StreamResult(sw));
        System.out.println(sw.toString());
    }