dom4j 解析xml 文件
<Root>
<mess>
<property name="sSize" value="52"></property>
<property name="cSize" value="23"></property>
<property name="pSize" value="15"></property>
<property name="aSize" value="25"></property>
</mess>
<table>
<property name="c" value="52c"></property>
<property name="a" value="23a"></property>
</table>
</Root>
package com.test.bao;
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.io.SAXReader;
public class OrgDomTest {
private static String path="src/com/test/bao/test.xml";
public String praseXml(String name) throws DocumentException{
SAXReader reader = new SAXReader();
//另外一種載入檔案路徑位置
InputStream is =null;
is= this.getClass().getClassLoader().getResourceAsStream(
"main/config/tablename.xml");
Document document = reader.read(new File(path));
Element root = document.getRootElement();
List<Element> emList= root.elements();
for(Element e:emList){
QName q=e.getQName();
if(q.getName().equals("mess")){
List<Element> childs=e.elements();
for(Element child:childs){
if(child.attributeValue("name").equals(name)){
return child.attributeValue("value");
}
}
}else if(q.getName().equals("table")){
List<Element> childs=e.elements();
for(Element child:childs){
if(child.attributeValue("name").equals(name)){
return child.attributeValue("value");
}
}
}
}
return null;
}
public static void main(String[] args) {
OrgDomTest org=new OrgDomTest();
try {
String name= org.praseXml("sSize");
String name1=org.praseXml("pSize");
String name2=org.praseXml("PSize");
System.out.println("輸出護具2 "+name2);
System.out.println("輸出護具1 "+name1);
System.out.println("輸出護具 "+name);
String name3=org.praseXml("c");
System.out.println("輸出table資料 "+ name3);
} catch (DocumentException e) {
e.printStackTrace();
}
}
}