Java code: use StAX to create xml file

The goal of this example is to produce the following xml file. The approach is through StAX API - XMLStreamWriter. It may be just a few seconds work to create an xml file by using StAX.

First Define City class

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;
    }
 
}

The code of using 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
	}
}

Here is a post about how to parse XML by using StAX XMLEventReader.

Category >> StAX  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>