[Java]
Package com. biztool;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. OutputStreamWriter;
Import java. io. Writer;
Import javax. xml. parsers. DocumentBuilder;
Import javax. xml. parsers. DocumentBuilderFactory;
Import javax. xml. transform. OutputKeys;
Import javax. xml. transform. Result;
Import javax. xml. transform. Source;
Import javax. xml. transform. Transformer;
Import javax. xml. transform. TransformerConfigurationException;
Import javax. xml. transform. TransformerException;
Import javax. xml. transform. TransformerFactory;
Import javax. xml. transform. dom. DOMSource;
Import javax. xml. transform. stream. StreamResult;
Import org. w3c. dom. Document;
Import org. w3c. dom. Element;
Import org. w3c. dom. Text;
Public class WriteXml {
Private void writeXMLFile (String xmlfile ){
File file = new File ("E:/tryfile/xml ");
File. listFiles ();
If (! File. exists ()){
File. mkdirs ();
}
DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance ();
DocumentBuilder dbuilder = null;
Try {
Dbuilder = dbf. newDocumentBuilder ();
} Catch (Exception ex ){
Ex. printStackTrace ();
}
Document doc = dbuilder. newDocument ();
Element root = doc. createElement ("student roster ");
Doc. appendChild (root );
Element stu = doc. createElement ("student ");
Stu. setAttribute ("gender", "male ");
Root. appendChild (stu );
Element stu_name = doc. createElement ("name ");
Stu. appendChild (stu_name );
Text name_text = doc. createTextNode ("Luo Wenwen ");
Stu_name.appendChild (name_text );
Element stu_age = doc. createElement ("Age ");
Stu. appendChild (stu_age );
Text age_text = doc. createTextNode ("25 ");
Stu_age.appendChild (age_text );
Try {
FileOutputStream fos = new FileOutputStream (xmlfile + "/test. xml ");
OutputStreamWriter osw = new OutputStreamWriter (fos );
CallDomWriter (doc, osw, "UTF-8 ");
Osw. close ();
Fos. close ();
} Catch (Exception ex ){
Ex. printStackTrace ();
}
}
Public void callDomWriter (Document dom, Writer writer, String encoding ){
Try {
Source source = new DOMSource (dom );
Result res = new StreamResult (writer );
Transformer xformer = TransformerFactory. newInstance (). newTransformer ();
Xformer. setOutputProperty (OutputKeys. ENCODING, encoding );
Xformer. transform (source, res );
} Catch (TransformerConfigurationException e ){
E. printStackTrace ();
} Catch (TransformerException e ){
E. printStackTrace ();
}
}
Public static void main (String [] args ){
WriteXml writeins = new WriteXml ();
String outfile = "E:/tryfile/xml ";
Writeins. writeXMLFile (outfile );
System. out. println ("finished ");
}
}