通过new创建xml文件_Java代码:使用StAX创建xml文件

d0a65be7d4c157150d46558a2ecdde8e.png

本示例的目标是产生以下xml文件。该方法是通过StAX API-XMLStreamWriter。使用StAX创建xml文件可能只需几秒钟的时间。

首先定义城市等级

class City{

private int id;

private String name;

public City() {

}

public City( int id, String name ) {

this.id = id;

this.name = name;

}

public int getId() {

return id;

}

public void setId( int id ) {

this.id = id;

}

public String getName() {

return name;

}

public void setName( String name ) {

this.name = name;

}

}

使用StAX API的代码。

public class Main {

public static void main(String[] args){

City c1 = new City(100, "Newark");

City c2 = new City(200, "New York");

ArrayList<City> l = new ArrayList<City>();

l.add(c1);

l.add(c2);

stAXToXml(l);

}

public static void stAXToXml(List<City> list) {

String xmlStr = null;

try {

if (null != list && !list.isEmpty()) {

StringWriter writerStr = new StringWriter();

// PrintWriter writerXml = new PrintWriter(new

// OutputStreamWriter( new FileOutputStream( "city-StAX.xml" ),

// "utf-8" ));

// define XMLEventWriter and XMLStreamWriter factory instance

XMLOutputFactory xof = XMLOutputFactory.newInstance();

// only one of the following is required.

XMLStreamWriter xmlsw = xof.createXMLStreamWriter(writerStr);

// XMLStreamWriter xmlsw = xof.createXMLStreamWriter( writerXml

// );

// write declaration

xmlsw.writeStartDocument("UTF-8", "1.0");

xmlsw.writeStartElement("cities");

// write comments

xmlsw.writeComment("city info");

for (City po : list) {

xmlsw.writeStartElement("city");

// add <id> node

xmlsw.writeStartElement(&quot;id&quot;);

xmlsw.writeCharacters(String.valueOf(po.getId()));

// end <id> node

xmlsw.writeEndElement();

// add <name> node

xmlsw.writeStartElement(&quot;name&quot;);

xmlsw.writeCharacters(po.getName());

// end <name> node

xmlsw.writeEndElement();

xmlsw.writeEndElement();

}

// end <cities> node

xmlsw.writeEndElement();

// end XML document

xmlsw.writeEndDocument();

xmlsw.flush();

xmlsw.close();

xmlStr = writerStr.getBuffer().toString();

writerStr.close();

}

} catch (XMLStreamException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

System.out.println(&quot;StAX:&quot; + xmlStr);// print result

}}

最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。

4b37a44a8d04e942a0625bf9dc06aff2.png

703e03fb2d814bbb692a3f4476c992c0.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值