使用Dom4j生成xml文件

public class Dom4JCreateXML {
	
	public static void main(String[] args) {
		
		Document document = DocumentHelper.createDocument();
		
		Element root = DocumentHelper.createElement("联系人列表");
		document.setRootElement(root);
		root.addAttribute("公司", "A集团");
		
		Element contact = DocumentHelper.createElement("联系人");
		root.add(contact);
		
		Element name = DocumentHelper.createElement("姓名");
		name.setText("张三");
		contact.add(name);

		Element company = DocumentHelper.createElement("公司");
		company.setText("A公司");
		contact.add(company);
		
//		Element telephone = DocumentHelper.createElement("电话");
//		telephone.setText("(021)5555666"); 
		contact.addElement("电话").setText("(021)5555666");	//等价于上面两行代码
		
		Element address = DocumentHelper.createElement("地址");
		address.addElement("街道").setText("5街");
		address.addElement("城市").setText("合肥市");
		address.addElement("省份").setText("安徽省");
		
		contact.add(address);
		
		try {

			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setIndent("    ");
			
			XMLWriter writer = new XMLWriter(new FileOutputStream("test.xml"),format);
			writer.write(document);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}


你可能感兴趣的:(使用Dom4j生成xml文件)