本示例的目標是產生以下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>();/<city>/<city>
l.add(c1);
l.add(c2);
stAXToXml(l);
}
public static void stAXToXml(List<city> list) {/<city>
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
xmlsw.writeStartElement("id");
xmlsw.writeCharacters(String.valueOf(po.getId()));
// end
xmlsw.writeEndElement();
// add <name> node/<name>
xmlsw.writeStartElement("name");
xmlsw.writeCharacters(po.getName());
// end <name> node/<name>
xmlsw.writeEndElement();
xmlsw.writeEndElement();
}
// end <cities> node/<cities>
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的資料與面試題,如果你在技術上面想提升自己的話,可以關注我,私信發送領取資料或者在評論區留下自己的聯繫方式,有時間記得幫我點下轉發讓跟多的人看到哦。
閱讀更多 軟帝學院一JAVA教學 的文章