XmlUtil


package demo;

import java.io.File;

import java.io.InputStream;

import java.net.MalformedURLException;

import java.net.URL;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

public class XmlUtil {

/**

     * 日志记录器

     */

    protected static Logger logger = (Logger) LoggerFactory.getLogger(XmlUtil.class);


/**

* 把输入流转换成xml文档对象

* @author:qiuchen

* @createTime:2012-7-5

* @param is

* @return

*/

public static Document parseToDocument(InputStream is) {

//xml解析器

SAXReader reader = new SAXReader();

//xml文档对象

Document document = null;

try {

document = reader.read(is);

if(is != null){

is.close();

}

} catch (Exception e) {

logger.warn(DateUtil.datetime()+"-- parseToDocument From InputStream ,SAXReader.read error");

return null;

}

return document;

}

/**

* 从url中读取xml文档对象

* @author:qiuchen

* @createTime:2012-7-5

* @param url

* @return

*/

public static Document parseToDocument(URL url) {

//xml解析器

SAXReader reader = new SAXReader();

//xml文档对象

Document document = null;

try {

document = reader.read(url);

} catch (Exception e) {

logger.warn(DateUtil.datetime()+"-- parseToDocument From URL:"+url+",SAXReader.read error");

return null;

}

return document;

}

 

 

/**

* 从字符串中加载Document对象

* @author:qiuchen

* @createTime:2012-9-24

* @param xmlPath xml文件路径

* @return

*/

public static Document stringToDoc(String str) {

Document doc = null;

try {

// 将xml格式化字符串转成Document对象

doc = DocumentHelper.parseText(str);

} catch (Exception ex) {

logger.warn(DateUtil.datetime()+"-- parseToDocument From str:"+str+",SAXReader.read error");

}

return doc;

}

 

/**

* 从文件中加载Document对象

* @author:qiuchen

* @createTime:2012-9-24

* @param xmlPath xml文件路径

* @return

*/

public static Document parseToDocument(String xmlPath){

File xmlFile = new File(xmlPath);

if(!xmlFile.exists()){

logger.warn(DateUtil.datetime()+"-- parseToDocument From xmlPath:"+xmlPath+",xmlPath not found");

return null;

}

//xml解析器

SAXReader reader = new SAXReader();

//xml文档对象

Document document = null;

try {

document = reader.read(xmlFile);

} catch (DocumentException e) {

logger.warn(DateUtil.datetime()+"-- parseToDocument From xmlPath:"+xmlPath+",SAXReader.read error");

return null;

}

return document;

}


}

你可能感兴趣的:(xml,document,dom4j,SAXReader,doc)