Dom解析xml,填充对象自己写的小例子

自己写的小程序,解析xml文件。但是对Element和Node 之间的区别。有一点不太明了。 还需要自己看API文档。
package com.util.XmlUtil;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DomDemo implements XmlDocument {

	private Document document;

	public void init() {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			this.document = builder.newDocument();
		} catch (ParserConfigurationException e) {
			System.out.println(e.getMessage());
		}
	}

	@Override
	public void createXml(String fileName) {
		Element root = this.document.createElement("employees");
		this.document.appendChild(root);
		Element employee = this.document.createElement("employee");
		Element name = this.document.createElement("name");
		name.appendChild(this.document.createTextNode("任俊明"));
		employee.appendChild(name);
		Element sex = this.document.createElement("sex");
		sex.appendChild(this.document.createTextNode("男"));
		employee.appendChild(sex);
		Element age = this.document.createElement("age");
		age.appendChild(this.document.createTextNode("23"));
		employee.appendChild(age);
		root.appendChild(employee);
		TransformerFactory tf = TransformerFactory.newInstance();

		try {
			Transformer transformer = tf.newTransformer();
			DOMSource source = new DOMSource(document);
			transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
			StreamResult result = new StreamResult(pw);
			transformer.transform(source, result);
			System.out.println("生成xml文件成功");
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {

		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public Employee parseXml(String fileName) {
		Employee ee = new DomDemo.Employee();
		try {
			// TODO Auto-generated method stub
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(fileName);
			NodeList nodeList = document.getChildNodes();
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node employee = nodeList.item(i);
				if (employee.getNodeType() != Node.TEXT_NODE) {
					NodeList employeeInfo = employee.getChildNodes();
					for (int j = 0; j < employeeInfo.getLength(); j++) {
						Node info = employeeInfo.item(j);
						if (info.getNodeType() != Node.TEXT_NODE) {
							NodeList infoList = info.getChildNodes();
							for (int k = 0; k < infoList.getLength(); k++) {
								Node attribute = infoList.item(k);
								if (attribute.getNodeType() != Node.TEXT_NODE) {
									String attributeName = attribute
											.getNodeName();
									if (attributeName.equals("name")) {
										ee.setName(attribute.getTextContent());
									} else if (attributeName.equals("sex")) {
										ee.setSex(attribute.getTextContent());
									} else if (attributeName.equals("age")) {
										ee.setAge(attribute.getTextContent());
									}
								}

							}
						}
					}
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
		return ee;
	}

	public List<Employee> parseXml2(String fileName) {
		List<Employee> list = new ArrayList<Employee>();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(fileName);
			NodeList nl = document.getElementsByTagName("employee");
			for (int i = 0; i < nl.getLength(); i++) {
				Employee ee = new DomDemo.Employee();
				Element employee = (Element) nl.item(i);
				Node nodeName = employee.getElementsByTagName("name").item(0);
				String name = nodeName.getFirstChild().getNodeValue();
				Node nodeSex = employee.getElementsByTagName("sex").item(0);
				String sex = nodeSex.getFirstChild().getNodeValue();
				Node nodeAge = employee.getElementsByTagName("age").item(0);
				String age = nodeAge.getFirstChild().getNodeValue();
				ee.setName(name);
				ee.setSex(sex);
				ee.setAge(age);
				list.add(ee);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	public static void main(String[] args) {
		String fileName = "employees.xml";
		DomDemo dd = new DomDemo();
		List<Employee> list = dd.parseXml2(fileName);
		Iterator<Employee> it = list.iterator();
		while (it.hasNext()) {
			Employee ee = (Employee) it.next();
			System.out.println(ee.getName());
			System.out.println(ee.getSex());
			System.out.println(ee.getAge());
		}
		// dd.init();
		// dd.createXml("employees.xml");
		/*
		 * Employee ee = dd.parseXml("employees.xml");
		 * System.out.println(ee.getName());
		 */
	}

	public class Employee {
		private String name;
		private String sex;
		private String age;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getSex() {
			return sex;
		}

		public void setSex(String sex) {
			this.sex = sex;
		}

		public String getAge() {
			return age;
		}

		public void setAge(String age) {
			this.age = age;
		}

	}

}

你可能感兴趣的:(dom解析xml)