本示例的目标是产生以下xml文件。该方法是通过StAX API-XMLStreamWriter。使用StAX创建xml文件可能只需几秒钟的时间。
首先定义城市等级
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的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。