import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XmlUtil {
private static Logger logger = Logger.getLogger(XmlUtil.class);
/**
* 使用sax解析本地xml文件
* @param fileName 文件名
* @return 是否解析成功
*/
public static boolean parseXmlBySax(String fileName){
//根据文件名称创建文件
File file = new File(fileName);
//创建文件输入流读取文件
FileInputStream fis = null;
SAXReader reader = null;
Document document = null;
if(!file.exists()){
logger.info("xml文件不存在");
return false;
}
try {
fis = new FileInputStream(file);
//根据解析文件的编码格式设置编码
reader.setEncoding("gbk");
reader = new SAXReader();
//通过文件输入流获取document
document = reader.read(fis);
//获取跟元素
Element rootElement = document.getRootElement();
//rootElement下包含的子元素
List<Element> list = rootElement.elements();
if(list != null && list.size()>0){
for(Element element:list){
//获取属性值(第一种方法)
Attribute attribute = element.attribute("name");
String value = attribute.getValue();
//获取属性值(第二种方法)
String newValue = element.attributeValue("name");
//获取element下的第一个userId元素
Element userElement = element.element("userId");
//获取userElement的文本
String text = userElement.getTextTrim();
//进行所需要的业务逻辑处理
}
return true;
}
} catch (FileNotFoundException e) {
logger.error("读取本地文件失败",e);
}catch(DocumentException e1){
logger.error("获取Document失败",e1);
}
return false;
}
}
原文:http://jameszhao1987.iteye.com/blog/1258461
生成、读取例子:http://inotgaoshou.iteye.com/blog/1012188
dom4j api详解:http://871421448.iteye.com/blog/1546955
附:微信公众号支付返回参数解析案例
public static JSONObject service(JSONObject params, ActionContext context) throws IOException, SQLException, NamingException{
HttpServletRequest req = (HttpServletRequest)context.get(ActionContext.REQUEST);
HttpServletResponse resp = (HttpServletResponse)context.get(ActionContext.RESPONSE);
resp.setContentType("text/xml;charset=utf-8");
resp.setCharacterEncoding("utf-8");
String out_trade_no = "";//商户订单号
String transaction_id="";//微信支付订单号
String result_code = "";
Element root=null;
try {
InputStream inputStream = req.getInputStream();
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
System.out.println(document.asXML());
root = document.getRootElement(); //获取跟元素
//rootElement下包含的子元素
result_code=root.element("result_code").getText();
out_trade_no=root.element("out_trade_no").getText();
transaction_id=root.element("transaction_id").getText();
} catch (DocumentException e) {
e.printStackTrace();
}
}