在某种情况下我们需要创建xml的时候保证其标签内部属性(attribute)的顺序不变,然而使用Java DOM Parser却不能实现该目的:
code:
location.setAttribute("plant", "P1");
location.setAttribute("plant_segment", "ASSEMBLY");
location.setAttribute("assembly_line", "AL1");
result:
<Location assembly_line="AL1" plant="P1" plant_segment="ASSEMBLY"/>
expected:
<Location plant="P1" plant_segment="ASSEMBLY" assembly_line="AL1"/>
为了实现这个目的,可以使用Jdom来创建Xml
maven jdom2:
<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
</dependency>
example:
public class TestSax{
@Test
public void testSAX() throws IOException {Element company = new Element("company");
Document doc = new Document(company);
Element staff = new Element("staff");
staff.setAttribute(new Attribute("id", "1"));
staff.addContent(new Element("firstname").setText("yong"));
staff.addContent(new Element("lastname").setText("mook kim"));
staff.addContent(new Element("nickname").setText("mkyong"));
staff.addContent(new Element("salary").setText("199999"));
doc.getRootElement().addContent(staff);
Element staff2 = new Element("staff");
staff2.setAttribute(new Attribute("id", "2"));
staff2.addContent(new Element("firstname").setText("low"));
staff2.addContent(new Element("lastname").setText("yin fong"));
staff2.addContent(new Element("nickname").setText("fong fong"));
staff2.addContent(new Element("salary").setText("188888"));
doc.getRootElement().addContent(staff2);
// new XMLOutputter().output(doc, System.out);
XMLOutputter xmlOutput = new XMLOutputter();
// display nice nice
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter("d:\\file.xml"));
System.out.println("File Saved!");
}
}
本文介绍如何使用Java的JDOM库创建XML文件时,保持元素属性的特定顺序,避免DOM解析器自动排序的问题。通过示例展示了如何定义和添加带有多个属性的元素,并使用XMLOutputter将Document对象输出到XML文件。
864

被折叠的 条评论
为什么被折叠?



