⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xmlprocessutil.java

📁 自己总结及编写调试好的程序,可直接应用 CutStringUtil截取字符串,能正确处理汉字定长处理 XMLProcessUtil 能处理XML读写文件的中文问题处理 服务器及客户端socket
💻 JAVA
字号:
package test;

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * XML 处理工具
 * 
 * @author zlh
 * 
 */
public class XmlProcessUtil {
	private Document document = null;

	/**
	 * 建立一个XML文档
	 * 
	 * @return Document
	 */
	public Document createXMLDocument() {
		/** 建立document对象 */
		document = DocumentHelper.createDocument();
		/** 建立XML文档的根rootName */
		Element booksElement = document.addElement("books");
		/** 加入一行注释 */
		booksElement.addComment("This is a test for dom4j, 测试.");

		// 加入第一个book节点 
		Element bookElement = booksElement.addElement("book");
		// 加入show属性内容
		bookElement.addAttribute("show", "yes");
		// 加入title节点 
		Element titleElement = bookElement.addElement("title");
		// 为title设置内容 
		titleElement.setText("Dom4j 测试");

		// 类似的完成后两个book 
		bookElement = booksElement.addElement("book");
		bookElement.addAttribute("show", "yes");
		titleElement = bookElement.addElement("title");
		titleElement.setText("Lucene Studing");
		bookElement = booksElement.addElement("book");
		bookElement.addAttribute("show", "no");
		titleElement = bookElement.addElement("title");
		titleElement.setText("Lucene in Action");

		// 加入owner节点 
		Element ownerElement = booksElement.addElement("owner");
		ownerElement.setText("O'Reilly");
		
		return document;
	}

	/**
	 * * 打开文档 *
	 * 
	 * @param filePath
	 *            文档路径
	 */
	public Document openXML(String filePath) {
		try {
			SAXReader saxReader = new SAXReader();
			this.document = saxReader.read(filePath);
			System.out.println("openXML(String filePath) successful ...");
		} catch (Exception e) {
			System.out.println("openXML() Exception:" + e.getMessage());
		}
		return this.document;
	}
	
	/**
	 * * 添加根节点的child *
	 * 
	 * @param nodeName
	 *            节点名 *
	 * @param nodeValue
	 *            节点值
	 */
	public void addNodeFromRoot(String nodeName, String nodeValue) {
		Element root = this.document.getRootElement();
		Element level1 = root.addElement(nodeName);
		level1.addText(nodeValue);
	}
	
	/**
	 * * 获得某个节点的值 *
	 * 
	 * @param nodeName
	 *            节点名称
	 */
	public String getElementValue(String nodeName) {
		try {
			Node node = document.selectSingleNode("//" + nodeName);
			return node.getText();
		} catch (Exception e1) {
			System.out
					.println("getElementValue() Exception:" + e1.getMessage());
			return null;
		}
	}

	/**
	 * * 获得某个节点的子节点的值 *
	 * 
	 * @param nodeName *
	 * @param childNodeName *
	 * @return
	 */
	public String getElementValue(String nodeName, String childNodeName) {
		try {
			Node node = this.document.selectSingleNode("//" + nodeName + "/"
					+ childNodeName);
			return node.getText();
		} catch (Exception e1) {
			System.out
					.println("getElementValue() Exception:" + e1.getMessage());
			return null;
		}
	}

	/**
	 * * 设置一个节点的text *
	 * 
	 * @param nodeName
	 *            节点名 *
	 * @param nodeValue
	 *            节点值
	 */
	public void setElementValue(String nodeName, String nodeValue) {
		try {
			Node node = this.document.selectSingleNode("//" + nodeName);
			node.setText(nodeValue);
		} catch (Exception e1) {
			System.out
					.println("setElementValue() Exception:" + e1.getMessage());
		}
	}

	/**
	 * * 设置一个节点值 *
	 * 
	 * @param nodeName
	 *            父节点名 *
	 * @param childNodeName
	 *            节点名 *
	 * @param nodeValue
	 *            节点值
	 */
	public void setElementValue(String nodeName, String childNodeName,
			String nodeValue) {
		try {
			Node node = this.document.selectSingleNode("//" + nodeName + "/"
					+ childNodeName);
			node.setText(nodeValue);
		} catch (Exception e1) {
			System.out
					.println("setElementValue() Exception:" + e1.getMessage());
		}
	}


	/**
	 * 
	 * @param filename
	 * @param document
	 * @return 成功返回 0, 失败返回 -1
	 */
	public int saveXMLFile(String filename, Document document,
			String xmlFileEncode) {
		int returnValue = -1;
		XMLWriter writer = null;
		String encode = xmlFileEncode;

		if (null == xmlFileEncode || "".equals(xmlFileEncode))
			encode = "GBK";

		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			/** 指定XML编码 */
			if ("GBK".equals(encode)) {
				format.setEncoding("GBK");
				writer = new XMLWriter(new FileWriter(filename), format);
			} else {
				// 如果是UTF-8 FileWriter 改用 FileOutputStream,否则在读取此XML时报错!
				format.setEncoding("UTF-8");
				writer = new XMLWriter(new FileOutputStream(filename), format);
			}
			writer.write(document);
			writer.close();

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

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		XmlProcessUtil x = new XmlProcessUtil();
		Document doc = x.createXMLDocument();
		x.saveXMLFile("c:\\test1.xml", doc, "GBK");
		doc = x.openXML("c:\\test1.xml");
		//System.out.println(x.getElementValue("owner",""));
		System.out.println(x.getElementValue("owner"));

		System.out.println(doc.selectSingleNode("//books/owner").getText());
		//System.out.println(doc.selectSingleNode("//books/book1/title1").getText());

		//下面测试遍历及修改
		 /** 修改内容之一: 如果book节点中show属性的内容为yes,则修改成no */
        /** 先用xpath查找对象 */
        List list = doc.selectNodes("/books/book/@show" ); 
        Iterator iter = list.iterator();
        while(iter.hasNext()){
           Attribute attribute = (Attribute)iter.next();
           System.out.println("attribute.getValue():"+attribute.getValue());
           if(attribute.getValue().equals("yes")){
               attribute.setValue("no");
           }   
        }

        
        /**
         * 修改内容之二: 把owner项内容改为test-modify.
         * 并在owner节点中加入date节点,date节点的内容为2008-03-31,还为date节点添加一个属性type
         */
        list = doc.selectNodes("/books/owner" );
        iter = list.iterator();
        if(iter.hasNext()){
           Element ownerElement = (Element)iter.next();
           ownerElement.setText("test-modify.");
           Element dateElement = ownerElement.addElement("date");
           dateElement.setText("2008-03-31");
           dateElement.addAttribute("type","Gregorian calendar");
        }

        /** 修改内容之三: 若title内容为book1'll remove.,则删除该节点 */
        list = doc.selectNodes("/books/book");
        iter = list.iterator();
        while(iter.hasNext()){
           Element bookElement = (Element)iter.next();
           Iterator iterator = bookElement.elementIterator("title");
           while(iterator.hasNext()){
               Element titleElement=(Element)iterator.next();
               if(titleElement.getText().equals("book1'll remove.")){
                  bookElement.remove(titleElement);
               }
           }
        }          
        
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -