DOM4J解析XML文档

 DOM4J解析XML文档实例:

 

public static void main(String[] args) throws IOException {
		//第一种方式创建文档并设置根元素节点
		/*Document document = DocumentHelper.createDocument();
		
		Element root = DocumentHelper.createElement("student");
		
		document.setRootElement(root);*/
		
		//第二种方式,创建文档并设置根节点
		Element root = DocumentHelper.createElement("student");
		
		Document document = DocumentHelper.createDocument(root);
		
		root.addAttribute("id", "1");
		
		Element name = root.addElement("name");
		Element age = root.addElement("age");
		
		name.setText("zhangsan");
		age.setText("15");
		
		//输出到控制台
		/*XMLWriter writer = new XMLWriter();
		writer.write(document);*/

		//输出到文件
		XMLWriter writer =new XMLWriter(new FileOutputStream("dom4j.xml"),new OutputFormat("    ",true));
		writer.write(document);
	}

 

 

你可能感兴趣的:(xml)