dom4j写入xml文件示例

public class WriteXML {


public static void main(String[] args) throws Exception
{
	 Document document = DocumentHelper.createDocument();
     document.setXMLEncoding("GBK");
     Element root = document.addElement("students");
     root.addNamespace("", "http://www.abc.com/ns/test");
     root.addNamespace("t", "http://www.abc.com/ns/test");
     root.addNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");
     root.addAttribute("xsi:schemaLocation", "http://www.abc.com/ns/test student.xsd");
     //QName qname = DocumentFactory.getInstance().createQName("schemaLocation", "xsi", "http://www.abc.com/ns/test student.xsd");
     //root.addAttribute(qname,"http://www.abc.com/ns/test student.xsd");


     Student[] s= new Student[5];


     s[0] = new Student("001", "za", "[email protected]", 50, 19, true);
     s[1] = new Student("002", "zb", "[email protected]", 51, 20, true);
     s[2] = new Student("003", "zc", "[email protected]", 52, 21, true);
     s[3] = new Student("004", "zd", "[email protected]", 53, 22, true);
     s[4] = new Student("005", "ze", "[email protected]", 54, 23, true);
     for (int i = 0; i < s.length; i++) {
         Student stu = s[i];
         Element e1 = root.addElement("student","http://www.abc.com/ns/test");
         
         //e1.addNamespace("", "http://www.abc.com/ns/test");
         
         Namespace n1 = e1.getNamespace();
         Namespace n2 = e1.getNamespaceForPrefix("");
         Namespace n3 = e1.getNamespaceForURI("http://www.abc.com/ns/test");
         //e1.remove(n1); e1.remove(n2); e1.remove(n3);
         
         e1.addElement("id").addText(stu.getId());
         e1.addElement("name").addText(stu.getName());
         e1.addElement("email").addText(stu.getEmail());
         e1.addElement("gender").addText(stu.getGender()?"男":"女");
         e1.addElement("age").addText(""+stu.getAge());
         e1.addElement("java").addText(""+stu.getJava());  
        }
     FileOutputStream fos = new FileOutputStream("student.xml");
     OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");
     OutputFormat of = new OutputFormat();
     of.setEncoding("GBK");
     of.setIndent(true);
     of.setIndent("    ");
     of.setNewlines(true);
     XMLWriter writer = new XMLWriter(osw, of);
     writer.write(document);
     writer.close();
    }
}

下面是生成的xml




    
        001
        za
        [email protected]
        
        19
        50
    
    
        002
        zb
        [email protected]
        
        20
        51
    
    
        003
        zc
        [email protected]
        
        21
        52
    
    
        004
        zd
        [email protected]
        
        22
        53
    
    
        005
        ze
        [email protected]
        
        23
        54
    



你可能感兴趣的:(JavaEE)