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

在某种情况下我们需要创建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!");
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值