java stax xml_Java代码:使用StAX创建xml文件

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

1d2b59b923b7f174354a7492447d4dd4.png

首先定义城市等级

classCity{

privateintid;

privateString name;

publicCity() {

}

publicCity( int id, String name ) {

this.id = id;

this.name = name;

publicintgetId() {

returnid;

publicvoidsetId( int id ) {

publicString getName() {

returnname;

publicvoidsetName( String name ) {

}

使用StAX API的代码。

publicclassMain {

publicstaticvoidmain(String[] args){

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

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

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

l.add(c1);

l.add(c2);

stAXToXml(l);

}

publicstaticvoidstAXToXml(List<City> list) {

String xmlStr = null;

try{

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

StringWriter writerStr = newStringWriter();

// 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 node

xmlsw.writeStartElement("id");

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

// end node

xmlsw.writeEndElement();

// add node

xmlsw.writeStartElement("name");

xmlsw.writeCharacters(po.getName());

// end node

// end node

// end XML document

xmlsw.writeEndDocument();

xmlsw.flush();

xmlsw.close();

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

writerStr.close();

} catch(XMLStreamException e) {

e.printStackTrace();

} catch(IOException e) {

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

}}

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

1e3b83112a2d945556a907433fd661ec.png

d6832454cf963e3e711256b5a6e90181.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值