Java创建xml的同时保证属性顺序不变

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/coderALEX/article/details/84290490

在某种情况下我们需要创建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!");
	}
}

猜你喜欢

转载自blog.csdn.net/coderALEX/article/details/84290490