本示例的目标是产生以下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("id");
xmlsw.writeCharacters(String.valueOf(po.getId()));
// end <id> node
xmlsw.writeEndElement();
// add <name> node
xmlsw.writeStartElement("name");
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("StAX:" + xmlStr);// print result
}}
最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。