Java:使用DOM4J解析XML

使用DOM解析;https://blog.csdn.net/chengmuzhe2690/article/details/83115600

Dom4J方式解析XML文件。dom4j是非官方提供的xml文件解析方式,因此需要去第三方下载dom4j的jar包

	File file = new File("D:\\chengmuzhe\\java\\JavaOOP6.0\\students.xml");
		SAXReader reader = new SAXReader();
		Document document = reader.read(file);
		Element root = document.getRootElement();
		try {
			System.out.println("学生信息:");
			for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
				Element element = (Element) iterator.next();
				String ids = element.elementText("stuId");
				
				System.out.println(ids);
				String names = element.elementText("stuName");
				System.out.println(names);
				String age = element.elementText("age");
				System.out.println(age);
				
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

读XML是还有一种方法就是使用Document的selectNodes来查找节点

使用这个方法是需要另外的包

导入xPath支持的jar包。jaxen-1.1-beta-6.jar(首先要先导入dom4j包,dom4j下载地址:http://www.dom4j.org/dom4j-1.6.1/)。下载jdom时在解压后的lib下
List lists = document.selectNodes("//students");
		Iterator iter = lists.iterator();
		while (iter.hasNext()) {
			Element element = (Element) iter.next();
				String ids = element.elementText("stuId");
				
				System.out.println(ids);
				String names = element.elementText("stuName");
				System.out.println(names);
				String age = element.elementText("age");
				System.out.println(age);
			
		}

写XML

	Document document = DocumentHelper.createDocument();
		Element element = document.addElement("students");
		Element studentElement = element.addElement("student");
		studentElement.addAttribute("email", "[email protected]");
		Element idElement = studentElement.addElement("stuId");
		idElement.setText("55");
		Element nameElement = studentElement.addElement("stuName");
		idElement.setText("55Name");
		Element ageElement = studentElement.addElement("age");
		ageElement.setText("55");
		try {
			XMLWriter output = new XMLWriter(new FileWriter(new File(
					"students2.xml")));
			output.write(document);
			output.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}

 

你可能感兴趣的:(java)