如果xml 节点是二级,或三级 那么解析 提取数据时很容易的 但是一旦xml节点多 特别是子节点 那么 这样提取数据的时候 有时候代码需要不断的循环 寻找
定位的精确度 也很麻烦 甚至 是定位混乱,所以 自己写了个工具类 来和大家分享 代码如下:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class XmlConfigurationUtil
{
private String configFileName;
private Element root;
private static XmlConfigurationUtil instance;
public String path;
public XmlConfigurationUtil(String configFileName)
throws Exception
{
this.configFileName = configFileName;
loadConfig(configFileName);
}
public List<Element> getList(String pattern)
{
List nodes = new ArrayList();
if (pattern.startsWith("//")) return nodes;
String[] paths = pattern.substring(1).split("/");
Element currentElement = null;
for (String path : paths) {
if (currentElement == null) {
currentElement = this.root;
if (!currentElement.getName().equals(path))
return nodes;
}
else
{
nodes = currentElement.getChildren(path);
if (nodes.size() <= 0) break;
currentElement = (Element)nodes.get(0);
}
}
return nodes;
}
public String getText(String pattern)
{
String text = "";
List ls = getList(pattern);
if (ls.size() > 0) {
text = ((Element)ls.get(0)).getTextNormalize();
}
return text;
}
private void loadConfig(String path)
throws Exception
{
System.out.println(path);
String basicwebConfig =
path;
Document doc = getFileDocument(basicwebConfig);
System.out.print("Load Config from: " + basicwebConfig);
if (doc == null) {
System.out.println("... Faild");
throw new Exception("ERROR *** File " + basicwebConfig + " not found or format wellformed ***");
}
this.root = doc.getRootElement();
System.out.println("... OK");
}
private Document getFileDocument(String sFilePath)
{
Document doc = null;
try {
FileInputStream in = new FileInputStream(sFilePath);
doc = new SAXBuilder().build(in);
} catch (IOException ex) {
ex.printStackTrace();
} catch (JDOMException ex) {
ex.printStackTrace();
}
return doc;
}
public static void main(String[] args){
try {
XmlConfigurationUtil s= new XmlConfigurationUtil("e:\\test.xml");
s.path="e:\\";
List<Element> list=s.getList("/ARTICLE/ARTICLE_INFO/BAN_ID");
System.out.println(list.get(0).getValue());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
main方法中List<Element> list=s.getList("/ARTICLE/ARTICLE_INFO/BAN_ID"); 意思就是
ARTICLE是最最父节点 然后下面就是一级一级的子节点 说道这里我想大家都已经明白了