public class SaxUtil {
//供调用的方法
public static String getMyNodeValue(String filepath, String xpath) throws SAXException, IOException, ParserConfigurationException {
SAXParserFactory sf = SAXParserFactory.newInstance();// 通过工厂获得SAX解析器
SAXParser sax = sf.newSAXParser();//解析器
SAXHander sh = new SaxUtil().new SAXHander(xpath);// 通过解析器解析xml文件
sax.parse(filepath, sh); //使用自定义的监听器
return sh.result;
}
//test main
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
// String xpath = "Manifest/Declaration/BorderTransportMeans/JourneyID";
// String filepath = "c:/CN_MT1101_1p0_COSCON_20090504130040082.xml";
String xpath = "NS1:CUSTXML/NS1:HEAD/NS1:FILLER2";
String filepath = "c:/O_F096F6986F80D711340DF0B4B082D396";
getMyNodeValue(filepath, xpath);
}
//自定义sax解析监听器
class SAXHander extends DefaultHandler {
private String mypath = null;
private String[] pps = null;
private int i = 0;
private String result = null;//结果
public SAXHander(String path) {
super();
this.mypath = path;
init();
}
private void init() {
if (mypath != null && !"".equals(mypath.trim())) {
pps = mypath.split("/");
}
}
public void startDocument() throws SAXException {
//System.out.println("文档开始 ");
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//System.out.println("元素开始 :" + qName);
if (pps != null && pps.length > 0) {
for (int j = 0; j < pps.length; j++) {
if (qName.equals(pps[j])) {
if (i == j)
i++;
}
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
String text = new String(ch, start, length);
//去掉xml文件中的空格节点
if (text.trim().equals("")) {
return;
}
if (pps != null && i == pps.length) {
result = text;
System.out.println("文本内容 :" + text);
i = -1;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
// System.out.println("元素结束 :" + qName);
}
public void endDocument() throws SAXException {
//System.out.println("文档结束 ");
}
}
}
用SAX取单个节点路径下的值
最新推荐文章于 2020-12-12 08:36:08 发布