import java.io.File;
java
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;
}
} api
原文:http://jameszhao1987.iteye.com/blog/1258461 微信
生成、讀取例子:http://inotgaoshou.iteye.com/blog/1012188 dom
dom4j api詳解:http://871421448.iteye.com/blog/1546955 ide
附:微信公衆號支付返回參數解析案例
微信支付
public static JSONObject service(JSONObject params, ActionContext context) throws IOException, SQLException, NamingException{編碼
HttpServletRequest req = (HttpServletRequest)context.get(ActionContext.REQUEST);spa
HttpServletResponse resp = (HttpServletResponse)context.get(ActionContext.RESPONSE);code
resp.setContentType("text/xml;charset=utf-8");orm
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();
}
}