通過jdom來解析,需要藉助第三方的組件.jdom.jar,網上有1.0的版本下載,這是我前幾天才寫的一段
public static hashmap<string, string> readxml(string path) {
hashmap<string, string> hamap = new hashmap<string, string>();
try {
document document = new saxreader().read(path);//找到xml的路徑
element root = document.getrootelement();//得到根節點
list member = root.elements();
if (null == member || 0 == member.size()) {
system.out.println("沒有子模組定義,系統退出");
return null;
}
//讀取xml中的值
string name;
string classname;
for (object e : member) {
name = ((element) e).attribute("name").getvalue();
classname = ((element) e).attribute("class").getvalue();
hamap.put(name, classname);
}
return hamap;
} catch (documentexception e) {
// todo auto-generated catch block
e.printstacktrace();
return null;
}
}
處理檔案
package cn.com.jdom;
import java.io.file;
import java.io.ioexception;
import java.util.iterator;
import java.util.list;
import org.jdom.attribute;
import org.jdom.document;
import org.jdom.element;
import org.jdom.jdomexception;
import org.jdom.processinginstruction;
import org.jdom.input.saxbuilder;
import com.sun.xml.internal.bind.v2.runtime.name;
/**
* jdom解析xml檔案
*
* @author 黃根華
*
*/
public class jdomxml {
public jdomxml() {
}
/**
* 解析xml檔案
* @param xmlfile
*/
public void parsexml(file xmlfile) {
saxbuilder sax = new saxbuilder();//在記憶體中建立一個sax文檔模型
try {
document xmldom = sax.build(xmlfile);//建立文檔
//獲得檔案的根項目
element root = xmldom.getrootelement();
system.out.println("根項目是:"+root.getname());
//獲得根項目的子節點
list childlist = root.getchildren();
iterator listit = childlist.iterator();
while(listit.hasnext()){
element element = (element)listit.next();
system.out.println("孩子結點是:"+element.getname());
}
//獲得第一個孩子結點
element firstchild = (element) childlist.get(0);
//獲得孩子結點的屬性
list attrlist = firstchild.getattributes();
iterator attrit = attrlist.iterator();
while(attrit.hasnext()){
attribute attr = (attribute ) attrit.next();
system.out.println("第一個元素的屬性是:"+attr.getname());
//獲得屬性的值
system.out.println("屬性的值是:"+attr.getvalue());
//獲得屬性的類型
system.out.println("屬性的類型是:"+attr.getattributetype());
}
list sonlist = firstchild.getchildren();
iterator sonit = sonlist.iterator();
while(sonit.hasnext()){
element temp = (element)sonit.next();
system.out.println("屬性"+temp.getname()+"的值是:"+temp.getvalue());
}
} catch (jdomexception e) {
e.printstacktrace();
} catch (ioexception e) {
e.printstacktrace();
}
}
public static void main(string[] args) {
jdomxml test = new jdomxml();
test.parsexml(new file("persons.xml"));
}
}
下面是xml檔案:
<?xml version="1.0" encoding="utf-8"?>
<persons>
<person perid="1001">
<name>lhu</name>
<age>89</age>
<address>安徽淮北</address>
<sex>男</sex>
</person>
<person perid="1002">
<name>we</name>
<age>56</age>
<address>北京海澱</address>
<sex>女</sex>
</person>
</persons>