1、实现将文件读取。
2、然后使用xpath进行解析。
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.XPath;
public class ParseXML {
/**
* 根据xpath表达式解析 xml
* @param document
* @param xpathExp
* @return
*/
public static String xpath(String xml, String xpathExp) {
Document document=null;
System.out.println(xml);
try {
document = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
e.printStackTrace();
}
XPath xpath = document.createXPath(xpathExp);
Node node = xpath.selectSingleNode(document);
if (node != null) {
//取值
String val = node.getStringValue();
// System.out.println(node.asXML());
return node.asXML();
}
return null;
}
/**
* 读取文件
* @param fileName
* @return
*/
public static String readFile(String fileName) {
StringBuilder sb = new StringBuilder();
InputStream f=null;
BufferedReader br=null;
try {
f = new FileInputStream(fileName);
br = new BufferedReader(new InputStreamReader(f));
String line="";
while ((line = br.readLine()) != null) {
sb.append(line);
}
if(sb.length()>0) {
return sb.toString();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(br!=null)
br.close();
if(br!=null)
f.close();
} catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
//将
String str = readFile("signpay.xml");
//获取signpay.xml中head的值
System.out.println(xpath(str,"/*/head"));
}
}