使用DOM4J解析和生成XML文件

1、生成XML文件

//生成XML
	
	private void createXML() {
		//创建document对象,代表证xml文件
		Document document =DocumentHelper.createDocument();
		//创建根节点rss
		Element rss = document.addElement("rss");
		//向rss中添加version属性
		rss.addAttribute("version", "2.0");
		//生成子节点及节点内容
		Element channel = rss.addElement("channel");
		Element title = channel.addElement("title");
		title.setText("国内新闻");
		//设置生成xml的格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		File file = new File("rss.xml");
		//生成xml文件
		XMLWriter writer;
		try {
			writer = new XMLWriter(new FileOutputStream(file),format);
			writer.write(document);
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

2、解析XML文件

//解析XML
	private void parseXML() {
		//①创建SAXReader 对象 reader
				SAXReader reader = new SAXReader();
				//②通过reader对象的read方法加载xml文件
				try {
					Document document=reader.read(new File("books.xml"));
					Element element = document.getRootElement();
					Iterator iter = element.elementIterator();
					while(iter.hasNext()) {
						Element book = (Element)iter.next();
						Listlist = book.attributes();
						for(Attribute attr:list) {
							System.out.println("节点名"+attr.getName()+"========="+"节点值"+attr.getValue());
						
						}
						Iterator bookstore = book.elementIterator();
						while(bookstore.hasNext()) {
							Element bookChild = (Element) bookstore.next();
							System.out.println("节点名"+bookChild.getName()+"++++++++++"+"节点值"+bookChild.getStringValue());
						}
					}
				} catch (DocumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

		
	}

 3、主函数调用

public static void main(String[] args) {
		// TODO 
		//生成xml文件
		new dom4j().createXML();
		//解析xml文件
		//new dom4j().parseXML();

	}

 

你可能感兴趣的:(Java天地)