import java.io.FileOutputStream; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class CreateXML { public static void main(String[] args) { String password="abc"; createXML(password); } /** *用Java代码写一个xml文件 */ public static void createXML(String password){ Document document=DocumentHelper.createDocument();//固定写法,创建一个文档 Element root=document.addElement("Request");//写根标签 /** * * xxx.addElement(String name);==>在xxx标签下添加名称为name的标签 * xxx.addAttribute(String key,String value);==>在xxx标签里添加key属性,值为value * */ Element Access=root.addElement("Access"); Element Authentication=Access.addElement("Authentication"); Authentication.addAttribute("user", "tiptop"); Authentication.addAttribute("password", password); Element Connection=Access.addElement("Connection"); Connection.addAttribute("application", "ApmtData"); Connection.addAttribute("source", "192.168.1.2"); Element Organization=Access.addElement("Organization"); Organization.addAttribute("name", "HDMNQ"); Element Locale=Access.addElement("Locale"); Locale.addAttribute("language", "zh_cn"); Element RequestContent=root.addElement("RequestContent"); Element Parameter=RequestContent.addElement("Parameter"); Element Record=Parameter.addElement("Record"); /*String[] str={"a","b","c","d","e"}; String[] str_name={"1","2","3","4","5"}; Element[] fields=new Element[str.length]; for (int i = 0; i < str.length; i++) { fields[i]=Record.addElement("Field"); fields[i].addAttribute("name", str_name[i]); fields[i].addAttribute("value", str[i]); } */ Element Field=Record.addElement("Field"); Field.addAttribute("name", "flag"); Field.addAttribute("value", "flag"); Element Field1=Record.addElement("Field"); Field1.addAttribute("name", "doc"); Field1.addAttribute("value", "T01-HMMN15040003"); Element Field2=Record.addElement("Field"); Field2.addAttribute("name", "status"); Field2.addAttribute("value", "S"); Element Document=RequestContent.addElement("Document"); XMLWriter writer=null; try { writer=new XMLWriter(OutputFormat.createPrettyPrint());//括号里的意思是有格式的输出 FileOutputStream fos=new FileOutputStream("F:\hd3.xml",false);//写到对应目录下的文件中,必须要存在路径,可以自动生成文件名 writer.setOutputStream(fos);//设置输出流 writer.write(document);//写出对应要写的xml文件内容 } catch (Exception e) { e.printStackTrace(); }finally{ if (writer!=null) { try { writer.close(); } catch (Exception e2) { e2.printStackTrace(); } } } } }