java W3C DOM解析XML

package com.netunit.workbench.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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 javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 对存储网元信息的XML进行操作
 * 
 * @author 何明
 * 
 */

public class HandleXML {

	private Element theNetunit = null;

	private Element theProperties = null;

	private Element root = null;

	public HandleXML() {

	}

	/**
	 * 增加网元
	 * 
	 * @param ip
	 * @param geteway
	 * @param subnet
	 * @param describe
	 * @return
	 */
	public int toWrite(String ip, String geteway, String subnet, String describe) {

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		try {

			factory.setIgnoringElementContentWhitespace(true);

			DocumentBuilder db = factory.newDocumentBuilder();

			File file = new File(
					"E:\\workspace\\com.netunit.workbench\\com.netunit.workbench\\com.netunit.workbench\\Info.xml");

			Document xmldoc = db.parse(file);

			root = xmldoc.getDocumentElement();

			// 新建网元

//			theNetunit = xmldoc.createElement("root");

			theNetunit = xmldoc.createElement("info");

			theNetunit.setAttribute("id", ip);

//			theNetunit.appendChild(theProperties);

			theProperties = xmldoc.createElement("IP");

			theProperties.setTextContent(ip);

			theNetunit.appendChild(theProperties);

			theProperties = xmldoc.createElement("gateway");

			theProperties.setTextContent(geteway);

			theNetunit.appendChild(theProperties);

			theProperties = xmldoc.createElement("subnet");

			theProperties.setTextContent(subnet);

			theNetunit.appendChild(theProperties);

			theProperties = xmldoc.createElement("describe");

			theProperties.setTextContent(describe);

			theNetunit.appendChild(theProperties);

			root.appendChild(theNetunit);

			output(theNetunit);

			saveXml(
					"E:\\workspace\\com.netunit.workbench\\com.netunit.workbench\\com.netunit.workbench\\Info.xml",
					xmldoc);

			return 1;

		} catch (Exception e) {

			e.printStackTrace();

		}

		return 0;

	}

	/**
	 * 根据IP查找其下面节点的值
	 * 
	 * @param ip
	 * @return
	 */
	public NetunitInfo getOtherMessage(String ip) {

		NetunitInfo info = new NetunitInfo();

		try {

			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			File file = new File(
					"E:\\workspace\\com.netunit.workbench\\com.netunit.workbench\\com.netunit.workbench\\Info.xml");

			Document doc = builder.parse(file);

			NodeList le = doc.getDocumentElement().getElementsByTagName("IP");

			for (int i = 0; i < le.getLength(); i++) {

				Node no = le.item(i);

				if (ip.equals(no.getFirstChild().getNodeValue())) {

					info.setIp(no.getFirstChild().getNodeValue());

					Node n = no.getNextSibling();

					info.setGateway(n.getNextSibling().getFirstChild()
							.getNodeValue());

					Node n1 = n.getNextSibling().getNextSibling();

					info.setSubnet(n1.getNextSibling().getFirstChild()
							.getNodeValue());

					Node n2 = n1.getNextSibling().getNextSibling();

					info.setDescribe(n2.getNextSibling().getFirstChild()
							.getNodeValue());

				}
			}

			return info;

		} catch (Exception e) {

			e.printStackTrace();

		}

		return null;
	}

	// 根据IP值修改其下面三个节点的值
	public int toUpdate(String ip, String gateway, String subnet,
			String describe) {

		try {

			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			File file = new File(
					"E:\\workspace\\com.netunit.workbench\\com.netunit.workbench\\com.netunit.workbench\\Info.xml");

			Document doc = builder.parse(file);

			NodeList le = doc.getDocumentElement().getElementsByTagName("IP");

			for (int i = 0; i < le.getLength(); i++) {

				Node no = le.item(i);

				if (ip.equals(no.getFirstChild().getNodeValue())) {

					Node n = no.getNextSibling();

					n.getNextSibling().getFirstChild().setNodeValue(gateway);

					Node n1 = n.getNextSibling().getNextSibling();

					n1.getNextSibling().getFirstChild().setNodeValue(subnet);

					Node n2 = n1.getNextSibling().getNextSibling();

					n2.getNextSibling().getFirstChild().setNodeValue(describe);

					saveXml(
							"E:\\workspace\\com.netunit.workbench\\com.netunit.workbench\\com.netunit.workbench\\Info.xml",
							doc);

				}

			}

			return 1;

		} catch (Exception e) {

			e.printStackTrace();

		}

		return 0;

	}

	// 根据IP删除节点信息
	public int toDelete(String ip) {

		try {

			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			File file = new File(
					"E:\\workspace\\com.netunit.workbench\\com.netunit.workbench\\com.netunit.workbench\\Info.xml");

			Document doc = builder.parse(file);
			
			NodeList le = doc.getElementsByTagName("info");
			
			for(int i = 0; i < le.getLength(); i++){
				
				Element e = (Element) le.item(i);
				
				if(ip.equals(e.getAttribute("id"))){
					
					e.getParentNode().removeChild(e);
					saveXml(
							"E:\\workspace\\com.netunit.workbench\\com.netunit.workbench\\com.netunit.workbench\\Info.xml",
							doc);
				}
				
			}

		} catch (Exception e) {

			e.printStackTrace();

		}

		return 0;

	}

	/**
	 * 将添加的信息打印在控制台
	 * 
	 * @param node
	 */
	public static void output(Node node) {
		TransformerFactory transFactory = TransformerFactory.newInstance();
		try {
			Transformer transformer = transFactory.newTransformer();
			transformer.setOutputProperty("encoding", "gb2312");
			transformer.setOutputProperty("indent", "yes");

			DOMSource source = new DOMSource();
			source.setNode(node);
			StreamResult result = new StreamResult();
			result.setOutputStream(System.out);

			transformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查找子节点
	 * 
	 * @param express
	 * @param source
	 * @return
	 */
	public static NodeList selectNodes(String express, Object source) {

		NodeList result = null;

		XPathFactory xpathFactory = XPathFactory.newInstance();

		XPath xpath = xpathFactory.newXPath();

		try {

			result = (NodeList) xpath.evaluate(express, source,
					XPathConstants.NODESET);

		} catch (XPathExpressionException e) {

			e.printStackTrace();

		}

		return result;
	}

	/**
	 * 得到节点值
	 * 
	 * @param key
	 * @return
	 */
	public static String[] getNodeValue(String key) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			File file = new File(
					"E:\\workspace\\com.netunit.workbench\\com.netunit.workbench\\com.netunit.workbench\\Info.xml");

			Document doc = builder.parse(file);

			String[] str = new String[doc.getDocumentElement()
					.getElementsByTagName("IP").getLength()];

			NodeList le = doc.getDocumentElement().getElementsByTagName("IP");
			for (int i = 0; i < le.getLength(); i++) {
				Node no = le.item(i);
				str[i] = no.getTextContent();
			}

			return str;

		} catch (Exception e) {

			e.printStackTrace();

		}
		return null;

	}

	/**
	 * 输出到文本
	 * 
	 * @param fileName
	 * @param doc
	 */
	public static void saveXml(String fileName, Document doc) {
		TransformerFactory transFactory = TransformerFactory.newInstance();
		try {
			Transformer transformer = transFactory.newTransformer();
			transformer.setOutputProperty("indent", "yes");

			DOMSource source = new DOMSource();
			source.setNode(doc);
			StreamResult result = new StreamResult();
			result.setOutputStream(new FileOutputStream(fileName));

			transformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {

		HandleXML hand = new HandleXML();

		// 添加
		// hand.toWrite("192.168.0.2", "192.168.0.1", "255.255.255.255",
		// "iiiiiiiiiiiiiip");

		hand.toDelete("192.168.0.1");
		
		// 读
		try {
			// DocumentBuilderFactory factory = DocumentBuilderFactory
			// .newInstance();
			// DocumentBuilder builder = factory.newDocumentBuilder();
			//
			// File file = new File("Info.xml");
			// Document doc = builder.parse(file);
			// String[] str = new
			// String[doc.getDocumentElement().getElementsByTagName("IP").getLength()];
			//			
			// System.out.println(str.length);
			//			
			// NodeList le =
			// doc.getDocumentElement().getElementsByTagName("IP");
			// for(int i=0;i<le.getLength();i++){
			// Node no = le.item(i);
			// System.out.println(no.getTextContent());
			// str[i] = no.getTextContent();
			// }
			// System.out.println(str.length);
			//
			//		
			//

			// 根据IP的值读其下面的三个节点的值
			// DocumentBuilderFactory factory = DocumentBuilderFactory
			// .newInstance();
			// DocumentBuilder builder = factory.newDocumentBuilder();
			//		
			// File file = new
			// File("E:\\workspace\\com.netunit.workbench\\com.netunit.workbench\\com.netunit.workbench\\Info.xml");
			//			
			// Document doc = builder.parse(file);
			//			
			// NodeList le =
			// doc.getDocumentElement().getElementsByTagName("IP");
			//			
			// for(int i=0;i<le.getLength();i++){
			// Node no = le.item(i);
			// System.out.println(no.getFirstChild().getNodeValue());
			// if("192.168.5.6".equals(no.getFirstChild().getNodeValue())){
			//					
			// NetunitInfo info = new NetunitInfo();
			//					
			// info.setIp(no.getFirstChild().getNodeValue());
			//					
			// Node n = no.getNextSibling();
			//					
			// info.setGateway(n.getNextSibling().getFirstChild().getNodeValue());
			//					
			// Node n1 = n.getNextSibling().getNextSibling();
			//					
			// System.out.println(n1.getNextSibling().getFirstChild().getNodeValue());
			// info.setSubnet(n1.getNextSibling().getFirstChild().getNodeValue());
			//					
			// Node n2 = n1.getNextSibling().getNextSibling();
			//					
			// System.out.println(n2.getNextSibling().getFirstChild().getNodeValue());
			//					
			// info.setDescribe(n2.getNextSibling().getFirstChild().getNodeValue());
			//					
			// }
			// }

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

}


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