随笔用dom4j建立,修改XML文档,

package com.rbt.action;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.struts2.ServletActionContext;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.rbt.common.util.FileUtil;
import com.rbt.common.util.PropertiesUtil;
import java.io.IOException;

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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class RegularlyUpdatedAction extends BaseAction {

	// 获取系统根目录
	static final String CLASS_PATH = PropertiesUtil.getClassPath();
	// 获取标签sql配置文件
	private static String file_names = "quartz_job.xml";
	private static String file_path = CLASS_PATH + file_names;
	private String allXmldateString = "";
	private String redXmlDateString = "";
	private String opdate;
	private String upallXmldataString = "";
	private static String xmlutfString = "<?xml version=\"1.0\" encoding=\"gb2312\"?>";
	private static String xmlnameString = "name";
	private static String xmlquartzString = "quartz";
	private static String xmldescriptionString = "mydescription";
	private static String xmlgroupString = "group";
	private static String xmljob_classString = "job-class";
	private static String xmljob_groupString = "job-group";
	private static String xmlcron_expressionString = "cron-expression";
	private static String xmltriggerString = "trigger";
	private static String xmljob_nameString = "job-name";
	private static String xmljob_detailString = "job-detail";
	private static String xmljobString = "job";
	private static String xmlcronString = "cron";
	FileUtil fileUtil;

	/**
	 * 方法描述:定时更新数据
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() throws Exception {
		readXML();
		if (allXmldateString != null && !allXmldateString.equals("")
				&& allXmldateString.length() > 4) {
			allXmldateString = allXmldateString.substring(0, allXmldateString
					.length() - 4);
		}
		if (redXmlDateString != null && !redXmlDateString.equals("")
				&& redXmlDateString.length() > 4) {
			redXmlDateString = redXmlDateString.substring(0, redXmlDateString
					.length() - 4);
		}
		//System.out.println("我需要的XML值:" + allXmldateString);
		return SUCCESS;
	}

	/**
	 * 方法描述:读取XML文件信息
	 */
	public void readXML() {
		try {
			File file = new File(file_path);// 创建文件对象
			SAXReader reader = new SAXReader();// 创建SAX阅读器
			Document doc = reader.read(file);// 读取内容生成Document对象
			Element root = doc.getRootElement();// 取得根节点
			search(root);// 开始遍历
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 递归遍历
	private void search(Element root) {
		String eNameString = "";
		String evalueString = "";
		Iterator it_element = root.elementIterator();// 将根节点下包含的元素组织成一个迭代器
		// 迭代
		while (it_element.hasNext()) {
			Element element = (Element) it_element.next();
			if (!element.getText().equals("")) {
				// System.out.println(element.getName() + "==节点的值是=="
				// + element.getText());
				if (element.getName().equals(xmlnameString)) {
					eNameString += element.getName() + "=" + element.getText()
							+ "##";
				}
				if (element.getName().equals(xmldescriptionString)) {
					eNameString += element.getName() + "=" + element.getText()
							+ "##";
					evalueString += element.getText() + "##";
				}
				if (element.getName().equals(xmlgroupString)) {
					eNameString += element.getName() + "=" + element.getText()
							+ "##";
				}
				if (element.getName().equals(xmljob_classString)) {
					eNameString += element.getName() + "=" + element.getText()
							+ "##";
				}
				if (element.getName().equals(xmljob_nameString)) {
					eNameString += element.getName() + "=" + element.getText()
							+ "##";
				}
				if (element.getName().equals(xmljob_groupString)) {
					eNameString += element.getName() + "=" + element.getText()
							+ "##";
				}
				if (element.getName().equals(xmlcron_expressionString)) {
					eNameString += element.getName() + "=" + element.getText()
							+ "##";
					evalueString += element.getText() + "##";
				}
			} else {
				System.out.println(element.getName() + "==节点");
			}
			search(element);// 递归调用
		}
		if (!eNameString.equals("")) {
			allXmldateString += eNameString + "&&";
		}
		if (!evalueString.equals("")) {
			redXmlDateString += evalueString + "&&";
		}
	}

	/**
	 * AJAX定时更新
	 * 
	 * @throws Exception
	 */
	public void updatedRegularly() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = ServletActionContext.getResponse().getWriter();
		String outputString = "1";
		try {
			File file = new File(file_path);// 创建文件对象
			SAXReader reader = new SAXReader();// 创建SAX阅读器
			Document doc = reader.read(file);// 读取内容生成Document对象
			/*
			 * 调用ModiXMLFiles()更新XML
			 */
			ModiXMLFiles(doc);
		} catch (Exception e) {
			// TODO: handle exception
			outputString = "2";
		}
		out.write(outputString);
		/*
		 * 调用modifXML()更新XML
		 */
		// try {
		// String filecontentString = modifXML();
		// fileUtil = new FileUtil();
		// fileUtil.writeTxt(CLASS_PATH, file_names, filecontentString);
		// File file = new File(file_path);// 创建文件对象
		// System.out.println("文件:" + file_names + "写入成功!");
		// } catch (Exception e) {
		// // TODO: handle exception
		// System.out.println("文件:" + file_names + "写入失败!");
		// outputString = "2";
		// }
		/*
		 * 调用modifXML()更新XML
		 */
		// String filecontentString = modifXML();
		// OutputFormat format = OutputFormat.createPrettyPrint();
		// /** 指定XML字符集编码 */
		// format.setEncoding("gb2312");
		// Document document = DocumentHelper.parseText(filecontentString);
		// XMLWriter writer = new XMLWriter(new FileWriter(file_path),format);
		// writer.write(document);
		// writer.close();
		/*
		 * 调用ModiXMLFile()更新XML
		 */
		// ModiXMLFile(file_path,file_path);
		

	}

	public void ModiXMLFiles(Document document) throws IOException {
		Element root = document.getRootElement(); // 得到根节点目录
		Iterator iter = root.elementIterator();
		String[] repvalueStrings = opdate.split("@@");
		Integer num = 0;
		//System.out.println("\r\n****** 获取的数据如下 ******");
		while (iter.hasNext()) {
			Element titleElement = (Element) iter.next();
			//System.out.println(titleElement.getName());
			// 读取xml的job元素
			if (titleElement.getName().equals(xmljobString)) {
				Iterator iter1 = titleElement.elementIterator();
				while (iter1.hasNext()) {
					Element titleElement1 = (Element) iter1.next();
					//System.out.println("1=:" + titleElement.getName());
					// 读取xml的trigger元素
					if (titleElement1.getName().equals(xmltriggerString)) {
						Iterator iter2 = titleElement1.elementIterator();
						while (iter2.hasNext()) {
							Element titleElement2 = (Element) iter2.next();
							//System.out.println("2=:" + titleElement2.getName());
							// 读取xml的cron元素
							if (titleElement2.getName().equals(xmlcronString)) {
								Iterator iter3 = titleElement2.elementIterator();
								while (iter3.hasNext()) {
									Element titleElement3 = (Element) iter3.next();
									//System.out.println("3=:"+ titleElement3.getName());
									// 读取xml的cron_expression元素
									if (titleElement3.getName().equals(xmlcron_expressionString)) {
										if (repvalueStrings[num] != null&& !repvalueStrings[num].toString().equals("")) {
											titleElement3.setText(repvalueStrings[num].toString());
										}
										num = num + 1;
									}
								}
							}
						}
					}
				}
			}
		}
		// 输出全部原始数据,在编译器中显示
		OutputFormat format = OutputFormat.createPrettyPrint();
		/** 指定XML字符集编码 */
		format.setEncoding("gb2312");
		// 输出全部原始数据,并用它生成新的我们需要的XML文件
		XMLWriter writer = new XMLWriter(new FileWriter(new File(file_path)),format);
		writer.write(document); // 输出到文件
		writer.close();
	}

	private String modifXML() {
		String allnewxmString = "";
		readXML();
		if (allXmldateString != null && !allXmldateString.equals("")
				&& allXmldateString.length() > 4) {
			allXmldateString = allXmldateString.substring(0, allXmldateString
					.length() - 4);
		}
		String newtitixmlString = xmlutfString;
		newtitixmlString += "<" + xmlquartzString + ">";
		String endtitlexmlString = "</" + xmlquartzString + ">";
		String newxmString = "";
		String[] strxmltexts = allXmldateString.split("##&&");
		String[] repvalueStrings = opdate.split("@@");
		for (int i = 0, ii = 0; i < strxmltexts.length; i = i + 2, ii++) {
			newxmString += "<" + xmljobString + ">";
			String models1 = "";
			String models2 = "";
			models1 = strxmltexts[i].toString();
			models2 = strxmltexts[i + 1].toString();
			String[] strmodel1 = models1.split("##");
			String[] strmodel2 = models2.split("##");
			newxmString += "<" + xmljob_detailString + ">";
			for (int j = 0; j < strmodel1.length; j++) {
				String[] strmodel11 = strmodel1[j].split("=");
				if (strmodel11 != null && strmodel11.length != 0) {
					if (strmodel11[0] != null) {
						newxmString += "<" + strmodel11[0].toString() + ">";
						if (strmodel11[1] != null) {
							newxmString += strmodel11[1].toString();
						}
						newxmString += "</" + strmodel11[0].toString() + ">";
					}
				}
			}
			newxmString += "</" + xmljob_detailString + ">";
			newxmString += "<" + xmltriggerString + ">";
			newxmString += "<" + xmlcronString + ">";
			for (int s = 0; s < strmodel2.length; s++) {
				String[] strmodel12 = strmodel2[s].split("=");
				if (strmodel12 != null && strmodel12.length != 0) {
					if (strmodel12[0] != null) {
						newxmString += "<" + strmodel12[0].toString() + ">";
						if (strmodel12[1] != null) {
							if (strmodel12[0].equals(xmlcron_expressionString)) {
								if (repvalueStrings[ii] != null) {
									newxmString += repvalueStrings[ii]
											.toString();
								} else {
									newxmString += strmodel12[1].toString();
								}
							} else {
								newxmString += strmodel12[1].toString();
							}
						}
						newxmString += "</" + strmodel12[0].toString() + ">";
					}
				}
			}
			newxmString += "</" + xmlcronString + ">";
			newxmString += "</" + xmltriggerString + ">";
			newxmString += "</" + xmljobString + ">";
		}
		allnewxmString = newtitixmlString + newxmString + endtitlexmlString;
		return allnewxmString;
	}

	/**
	 * 修改XML文件中内容,并另存为一个新文件 重点掌握dom4j中如何添加节点,修改节点,删除节点
	 * 
	 * @param filename
	 *            修改对象文件
	 * @param newfilename
	 *            修改后另存为该文件
	 * @return 返回操作结果, 0表失败, 1表成功
	 */
	public int ModiXMLFile(String filename, String newfilename) {
		int returnValue = 0;
		String[] repvalueStrings = opdate.split("@@");
		int num = 0;
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(new File(filename));
			/**
			 * 修改内容: 修改cron-expression项内容
			 */
			List list = document.selectNodes("cron-expression");
			Iterator iter = list.iterator();
			if (iter.hasNext()) {
				Element ownerElement = (Element) iter.next();
				ownerElement.setText(repvalueStrings[num]);
				num = num + 1;
			}
			try {
				OutputFormat format = OutputFormat.createPrettyPrint();
				/** 指定XML字符集编码 */
				format.setEncoding("gb2312");
				/** 将document中的内容写入文件中 */
				XMLWriter writer = new XMLWriter(new FileWriter(new File(
						newfilename)), format);
				writer.write(document);
				writer.close();
				/** 执行成功,需返回1 */
				returnValue = 1;
			} catch (Exception ex) {
				ex.printStackTrace();
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return returnValue;
	}

	public int formatXMLFile(String filename) {
		int returnValue = 0;
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(new File(filename));
			XMLWriter output = null;
			/** 格式化输出,类型IE浏览一样 */
			OutputFormat format = OutputFormat.createPrettyPrint();
			/** 指定XML字符集编码 */
			format.setEncoding("utf-8");
			output = new XMLWriter(new FileWriter(new File(filename)), format);
			output.write(document);
			output.close();
			/** 执行成功,需返回1 */
			returnValue = 1;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return returnValue;
	}

	public String getAllXmldateString() {
		return allXmldateString;
	}

	public void setAllXmldateString(String allXmldateString) {
		this.allXmldateString = allXmldateString;
	}

	public String getRedXmlDateString() {
		return redXmlDateString;
	}

	public void setRedXmlDateString(String redXmlDateString) {
		this.redXmlDateString = redXmlDateString;
	}

	public String getOpdate() {
		return opdate;
	}

	public void setOpdate(String opdate) {
		this.opdate = opdate;
	}

	public String getUpallXmldataString() {
		return upallXmldataString;
	}

	public void setUpallXmldataString(String upallXmldataString) {
		this.upallXmldataString = upallXmldataString;
	}

}

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