Java建立XML文件的SAX方式
package cn.rock.service;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
public class SAXCreateService {
public void SAXCreateXML(){
XMLOutputFactory factory = XMLOutputFactory.newInstance();
try {
XMLStreamWriter xmlWriter = factory.createXMLStreamWriter(new FileOutputStream("D:\\person.xml"));
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement("persons");
for(int i=0; i<3; i++){
xmlWriter.writeStartElement("person" + i);
xmlWriter.writeAttribute("id", "20");
xmlWriter.writeStartElement("name");
xmlWriter.writeCharacters("rock" + i);
xmlWriter.writeEndElement();
xmlWriter.writeStartElement("age");
xmlWriter.writeCharacters("15");
xmlWriter.writeEndElement();
xmlWriter.writeEndElement();
}
xmlWriter.writeEndDocument();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMLStreamException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}