XStream工具生成XML文件(标签中添加属性)

1、添加实体类

@XStreamAlias("item")
public class Item implements Serializable{
	@XStreamAlias("free1")
	private String free1;
	@XStreamAlias("free2")
	private String free2;
	//item标签下包含多个ass
	@XStreamImplicit(itemFieldName="ass")
	private List<Ass> ass;
	public String getFree1() {
		return free1;
	}
	public void setFree1(String free1) {
		this.free1 = free1;
	}
	public String getFree2() {
		return free2;
	}
		public List<Ass> getAss() {
		return ass;
	}
	public void setAss(List<Ass> ass) {
		this.ass = ass;
	}
}
@XStreamAlias("ass")
public class Ass implements Serializable{
	@XStreamImplicit(itemFieldName="item")
	private List<Item> items;

	public List<Item> getItem() {
		return items;
	}

	public void setItem(List<Item> items) {
		this.items = items;
	}

	
}

2、编写工具类

public class Test {
	public static void main(String[] args) {
	Item item=new Item();
	item.setFree1("154591486468168469854687614668");
	item.setFree2("154591486468168469854687614668");
	Ass ass=new Ass();
	List<Item> items =new ArrayList<>();
	items.add(item);
	ass.setItem(items);
	Item item1=new Item();
	List<Ass> asss=new ArrayList<>();
	asss.add(ass);
	item1.setAss(asss);
	XStream xStream = new XStream();
	xStream.autodetectAnnotations(true);
	//设置标签里属性
	xStream.useAttributeFor(Item.class,"free");
	String xml = xStream.toXML(voucher);
		try {
			strChangeXML(xml);
		} catch (IOException e) {
			e.printStackTrace();
		}
}
 //将字符串string类型转换成xml文件
    public static void strChangeXML(String str) throws IOException {
           SAXReader saxReader = new SAXReader();
           Document document;
           try {
            document = saxReader.read(new ByteArrayInputStream(str.getBytes("UTF-8")));
            OutputFormat format = OutputFormat.createPrettyPrint();
            /** 将document中的内容写入文件中 */
            XMLWriter writer = new XMLWriter(new FileWriter(new File("D:/cctv.xml")),format);
            writer.write(document);
            writer.close();
           } catch (DocumentException e) {
            e.printStackTrace();
           }
   }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值