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

📄 xmlutil.java

📁 XMLUtil.java/ java 解析XML源码
💻 JAVA
字号:
package com.asiainfo.aiox.ovsd.common;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;public class XMLUtil {    private static Log logger = LogFactory.getLog(XMLUtil.class);	public XMLUtil() {		super();		// TODO Auto-generated constructor stub	}	/**	 * 将fromPath文件夹中的filename文件,移除到toPath	 * @param fromPath String 源文件目录 d:\\temp\\source	 * @param toPath String 目标文件目录 d:\\temp\\bak	 * @param name String 要移动的文件 EVT_HELLO.txt	 * @throws IOException 	 */	public static void moveFile(String fromPath, String toPath, String filename) throws IOException {				/**源文件*/		String sourceFileName=fromPath+File.separatorChar+filename;		String bakFileName=toPath+File.separatorChar+filename;		File sourceFile=new File(sourceFileName);		if(!sourceFile.exists())			return;		mkdir(toPath);				String tmpBakFileName=bakFileName+".tmp";		createNewFile(tmpBakFileName);					/** 开始拷贝复制 */		FileInputStream fis = new FileInputStream(sourceFile);		FileOutputStream fos = new FileOutputStream(new File(tmpBakFileName));		byte[] buf = new byte[1024];		int i = 0;		while ((i = fis.read(buf)) != -1) {			fos.write(buf, 0, i);		}		fis.close();		fos.close();		sourceFile.delete();		File file=new File(tmpBakFileName);		File destFile=new File(bakFileName);		if(destFile.exists())			destFile.delete();		file.renameTo(destFile);	}	/**	 * 创建文件目录	 * @param folderPath	 */	public static void mkdir(String folderPath)	{		File file=new File(folderPath);		if(!file.exists())			file.mkdirs();	}	/**	 * 创建文件,如果原先存在,则删除该文件	 * @param filename String 文件的绝对路径	 * @throws IOException 	 */	public static void createNewFile(String filename) throws IOException	{		File file=new File(filename);		if(file.exists())			file.delete();		else			file.createNewFile();	}	/**	 * <p>	 * 将dom4j节点根据encoding格式保存到文件filename中	 * </p>	 * 	 * @param root	 *            Element 根节点	 * @param filename	 *            String 待保存文件的绝对路径及文件名	 * @param encoding	 *            String 待保存文件的格式,null或""的时候为"utf-8"格式	 * @return	 * @throws IOException	 */	public static void writeToFile(Element root, String filename,			String encoding) throws IOException {		int pos = filename.lastIndexOf(File.separatorChar);		String path = filename.substring(0, pos);		mkdir(path);		createNewFile(filename);		Document document = root.getDocument();		if(document==null)		{				document=DocumentHelper.createDocument();			document.add(root);		}		OutputFormat format = OutputFormat.createPrettyPrint();		if (encoding == null || "".equals(encoding.trim()))			format.setEncoding("utf-8");		else			format.setEncoding(encoding);		XMLWriter writer = new XMLWriter(new FileOutputStream(filename), format);		writer.write(document);		writer.close();	}      /**     * <root> <a> <b></b> <b></b></a><a><a> <root>      * 如果想得到第2个Element b,xPath的格式为“/a@1/b@2”     *      * @param root     * @param xPath     * @return     */    public static List getNodeList(Element root, String xPath)    {        String helpMessage ="Parameter error."+            "For instance:     \n"                     + "* <root> \n"                    + "*     <a>\n"                     + "*        <b>\n"                     + "*        </b>\n"                    + "*        <b>\n"                     + "*        </b>\n"                    + "*     </a>\n"                     + "*     <a>\n"                     + "*     </a>\n"                     + "* <root>\n"                    + "* if want to get the second Element b,the xPath should be like “/a@1/b@2”";        if (root == null || xPath == null || !xPath.startsWith("/"))        {            logger.error(helpMessage);            return null;        }        String[] paths = xPath.split("/");        List result = new ArrayList();        List tempResult =null;        int which = 1;        boolean isSet = false;        String temp = null;        for (int i = 1; i < paths.length; i++)        {            paths[i] = paths[i].trim();            if (paths[i].length() == 0)            {                logger.error("The path value '"+xPath+"' is wrong !");                logger.error(helpMessage);                return null;            }            if (paths[i].indexOf("@") != -1)            {                temp = paths[i].substring(paths[i].indexOf("@") + 1);                                try                {                    which = Integer.parseInt(temp);                    isSet = true;                }                catch (NumberFormatException e)                {                    logger.error("The path value " + paths[i]                            + " is wrong!");                    return null;                }                                paths[i] = paths[i].substring(0,paths[i].indexOf("@"));            }            tempResult = root.elements(paths[i]);            if (tempResult == null || tempResult.size() < 1)            {                logger.error("Can't find this element,root = "                        + root.getName() + ";path = " + paths[i]);                return null;            }            if (which > tempResult.size() || which <= 0)            {                logger.error("The sequence '" + which + "' of path value '"                        + paths[i] + "' is wrong!");                return null;            }            if( i == paths.length -1)            {                if (isSet)                {                    result.clear();                    result.add(tempResult.get(which-1));                }                else                {                    result = tempResult;                }            }            else            {                root = (Element) tempResult.get(which-1);             }            isSet = false;            which = 1;        }        return result;    }}

⌨️ 快捷键说明

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