生成及解析XML

package com.test.xml;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.dom4j.DocumentHelper;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.sun.org.apache.xerces.internal.dom.DocumentImpl;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

/**
 * 
 * @author john
 * 
 *         测试java生成XML文件
 * 
 */
public class XMLManager {

	long startTime;
	long endTime;

	/**
	 * 使用BufferedWriter往文件中写数据
	 * 
	 * @param strFileName
	 */
	public void createXMLByString(String strFileName) {
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(strFileName);
			bw = new BufferedWriter(fw);
			bw.write("<?xml version='1.0' encoding='gb2312' ?>");
			bw.newLine(); // 下一行
			bw.write("<电脑配置>");
			bw.newLine();
			bw.write("        <DELL type='台式机'>"); // 留出空间
			bw.newLine();
			bw.write("            <CPU type='四核'>Intel</CPU>");
			bw.newLine();
			bw.write("            <内存 type='4G'>金士顿</内存>");
			bw.newLine();
			bw.write("            <硬盘 type='500G'>西部数据</硬盘>");
			bw.newLine();
			bw.write("        </DELL>");
			bw.newLine();
			bw.write("        <DELL type='笔记本'>");
			bw.newLine();
			bw.write("            <CPU type='双核'>AMD</CPU>");
			bw.newLine();
			bw.write("            <内存 type='2G'>三星</内存>");
			bw.newLine();
			bw.write("            <硬盘 type='500G'>西部数据</硬盘>");
			bw.newLine();
			bw.write("        </DELL>");
			bw.newLine();
			bw.write("</电脑配置>");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				bw.close();
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 生成XML
	 * 
	 * @param strFileName
	 *            要创建的xml文件名
	 */
	public void createXMLByDom(String strFileName) {
		Document doc = new DocumentImpl();
		Element root = doc.createElement("Root"); // 创建根节点
		root.setAttribute("type", "root"); // 加入属性
		doc.appendChild(root);

		for (int i = 0; i < 10; i++) {
			Element child = doc.createElement("Child"); // 创建子节点
			child.setTextContent("chlid" + i); // 创建节点内容
			child.setAttribute("type", "child"); // 创建节点属性
			child.setAttribute("name", "chlid" + i);
			if (i == 5) {
				child.setNodeValue("6");
			}
			root.appendChild(child);
		}

		File outputFile = new File(strFileName); // 指定要生成的文件
		OutputFormat outputFormat = new OutputFormat("XML", "gb2312", true); // XML编码方式,每个节点是否换行
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(outputFile);
			XMLSerializer xmlSerializer = new XMLSerializer(fileWriter,
					outputFormat);
			xmlSerializer.asDOMSerializer();
			xmlSerializer.serialize(doc.getDocumentElement());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				fileWriter.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 使用Dom4j生成xml
	 * 
	 * @param strFileName
	 */
	public void createXMLByDom4j(String strFileName) {
		org.dom4j.Document doc = DocumentHelper.createDocument();
		org.dom4j.Element root = doc.addElement("电脑配置"); // 生成主节点
		root.addComment("this is compute xml file");
		org.dom4j.Element ele1 = root.addElement("DELL"); // 加上子节点
		ele1.addAttribute("type", "台式机");
		org.dom4j.Element sub1Ele1 = ele1.addElement("CPU");
		sub1Ele1.addAttribute("type", "四核"); // 属性
		sub1Ele1.setText("Intel"); // 值
		org.dom4j.Element sub2Ele1 = ele1.addElement("内存");
		sub2Ele1.addAttribute("type", "4G");
		sub2Ele1.setText("金士顿");
		org.dom4j.Element sub3Ele1 = ele1.addElement("硬盘");
		sub3Ele1.addAttribute("type", "500G");
		sub3Ele1.setText("西部数据");

		org.dom4j.Element ele2 = root.addElement("DELL");
		ele2.addAttribute("type", "笔记本");
		org.dom4j.Element sub1Ele2 = ele2.addElement("CPU");
		sub1Ele2.addAttribute("type", "双核");
		sub1Ele2.setText("AMD");
		org.dom4j.Element sub2Ele2 = ele2.addElement("内存");
		sub2Ele2.addAttribute("type", "2G");
		sub2Ele2.setText("三星");
		org.dom4j.Element sub3Ele2 = ele2.addElement("硬盘");
		sub3Ele2.addAttribute("type", "500G");
		sub3Ele2.setText("西部数据");

		XMLWriter writer = null;
		org.dom4j.io.OutputFormat format = org.dom4j.io.OutputFormat
				.createPrettyPrint(); // 使用OutputFormat的Pretty格式
		try {
			writer = new XMLWriter(new FileWriter(new File(strFileName)),
					format);
			writer.write(doc);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void createXMLByJDom(String strFileName) {
		org.jdom.Element root = new org.jdom.Element("电脑配置"); // 生成主节点
		org.jdom.Document doc = new org.jdom.Document(root); // 主节点加入文件中
		org.jdom.Element ele1 = new org.jdom.Element("DELL");
		ele1.setAttribute("type", "台式机");
		ele1.addContent(new org.jdom.Element("CPU").setAttribute("type", "四核")
				.setText("Intel")); // 节点加入子节点,属性及值
		ele1.addContent(new org.jdom.Element("内存").setAttribute("type", "4G")
				.setText("金士顿"));
		ele1.addContent(new org.jdom.Element("硬盘").setAttribute("type", "500G")
				.setText("西部数据"));
		root.addContent(ele1);

		org.jdom.Element ele2 = new org.jdom.Element("DELL");
		ele2.setAttribute("type", "笔记本");
		ele2.addContent(new org.jdom.Element("CPU").setAttribute("type", "双核")
				.setText("AMD"));
		ele2.addContent(new org.jdom.Element("内存").setAttribute("type", "2G")
				.setText("三星"));
		ele2.addContent(new org.jdom.Element("硬盘").setAttribute("type", "500G")
				.setText("西部数据"));
		root.addContent(ele2);

		XMLOutputter XMLOut = new XMLOutputter();
		Format format = Format.getPrettyFormat(); // 使用pretty格式
		// format.setEncoding("GB2312"); //可以设置编码
		XMLOut.setFormat(format);

		try {
			XMLOut.output(doc, new FileOutputStream(strFileName));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 
	 * 读取xml并打印主要节点数据
	 * 
	 * @param fileName
	 *            要读取的xml文件名
	 */
	public void readXMLByDom(String fileName) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;
		try {
			db = dbf.newDocumentBuilder();
			Document doc = db.parse(new File(fileName));
			Element element = doc.getDocumentElement();
			System.out.println("根元素为:" + element.getTagName());
			NodeList nodeList = doc.getElementsByTagName("DELL");
			System.out.println("DELL节点的长度:" + nodeList.getLength());
			Node fatherNode = nodeList.item(0);
			System.out.println("父节点为:" + fatherNode.getNodeName());
			// 把父节点的属性拿出来
			NamedNodeMap attributes = fatherNode.getAttributes();
			for (int i = 0; i < attributes.getLength(); i++) {
				Node attribute = attributes.item(i);
				System.out.println("DELL的属性名为:" + attribute.getNodeName()
						+ " 相对应的属性值为:" + attribute.getNodeValue());
			}
			NodeList childNodes = fatherNode.getChildNodes();
			System.out.println(childNodes.getLength());
			for (int j = 0; j < childNodes.getLength(); j++) {
				Node childNode = childNodes.item(j);
				// 如果这个节点属于Element ,再进行取值
				if (childNode instanceof Element) {
					System.out.println("子节点名为:" + childNode.getNodeName()
							+ " 相对应的值为"
							+ childNode.getFirstChild().getNodeValue());
				}
			}

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

	public void readXMLByDom4j(String fileName) {
		startTime = System.nanoTime();
		try {
			File f = new File(fileName);
			SAXReader reader = new SAXReader();
			org.dom4j.Document doc = reader.read(f);
			org.dom4j.Element root = doc.getRootElement();
			org.dom4j.Element foo = null;
			for (Iterator i = root.elementIterator("DELL"); i.hasNext();) {
				foo = (org.dom4j.Element) i.next();
				System.out.println("电脑类型:" + foo.attributeValue("type"));
				System.out.println("CPU:" + foo.elementText("CPU"));
				System.out.println("内存:" + foo.elementText("内存"));
				System.out.println("硬盘:" + foo.elementText("硬盘"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		endTime = System.nanoTime();
		System.out.println("通过Dom4j读取xml所用的时间:" + (endTime - startTime));
	}

	public void readXMLByJDom(String fileName) {
		startTime = System.nanoTime();
		try {
			SAXBuilder builder = new SAXBuilder();
			org.jdom.Document doc = builder.build(new File(fileName));
			org.jdom.Element foo = doc.getRootElement();
			List<org.jdom.Element> allChildren = foo.getChildren();
			for (int i = 0; i < allChildren.size(); i++) {
				System.out.println("电脑类型:"
						+ ((org.jdom.Element) allChildren.get(i))
								.getAttributeValue("type"));
				System.out.println("CPU:"
						+ ((org.jdom.Element) allChildren.get(i)).getChild(
								"CPU").getText());
				System.out.println("内存:"
						+ ((org.jdom.Element) allChildren.get(i))
								.getChild("内存").getText());
				System.out.println("硬盘:"
						+ ((org.jdom.Element) allChildren.get(i))
								.getChild("硬盘").getText());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		endTime = System.nanoTime();
		System.out.println("通过JDom读取xml所用的时间:" + (endTime - startTime));
	}

	public static void main(String[] argus) {
		XMLManager manager = new XMLManager();
		// manager.createXML("E:\\学习XML\\test1.xml");
		// manager.readXMLByDom("E:\\学习XML\\Computer.xml");
		// manager.readXMLByJDom("E:\\学习XML\\Computer.xml");
		// manager.readXMLByDom4j("E:\\学习XML\\Computer.xml");
		// manager.createXMLByString("E:\\学习XML\\Computer1.xml");
		// manager.createXMLByDom4j("E:\\学习XML\\Computer2.xml");
		manager.createXMLByJDom("E:\\学习XML\\Computer3.xml");
	}
}

你可能感兴趣的:(java,apache,xml,sun)