java读取xml文件
第一:写好文件为one.xml,内容如下:
<a>
<b>
<c1>
<First id="1" name='"one">
<First id="2" name='"two">
<First id="31" name='"three">
</c1>
<c2>
#与上面的First类似
</c2>
</b>
</a>
第二:写好一个类First.java,里面有两个属性id和name,然后get和set方法。
第三:再写一个类为Test.java。写main方法,在main方法里写入
SAXReader saXReader = new SAXReader();
URL realUrl = RateContext.class.getClassLoader().getResource("\\one.xml");
Document doc;
try {
doc = saXReader.read(realUrl);
List<First> list = new ArrayList<First>();
String path="/a/b/c1";
List<First> list1=rc.addEle(path, list, First.class,doc);;
for(int i=0;i<list1.size();i++){
System.out.println(list1.get(i).getId()+" , "+list1.get(i).getName());
}
} catch (DocumentException e) {
e.printStackTrace();
}
第四:另外在这个Test.java中写两个方法
public static List addEle(String xPath, List list, Class clazz,Document doc) {
List<Element> Info = XmlHelper.parseXmlEleByXpath(doc, xPath);
Field[] fields = clazz.getDeclaredFields();
for (Element e : Info) {
try {
Object object = clazz.newInstance();
for (Field field : fields) {
Method method = clazz.getMethod("set"
+ toUpperCase(field.getName()), field.getType());
if(field.getType().getName().equals("int")){
method.invoke(object, new Object[] {Integer.parseInt(e.attributeValue(field
.getName()) )});
}else{
method.invoke(object, new Object[] {e.attributeValue(field
.getName()) });
}
}
list.add(object);
} catch (SecurityException e1) {
logger.info(e1.getMessage(), e1);
} catch (NoSuchMethodException e2) {
logger.info(e2.getMessage(), e2);
} catch (IllegalArgumentException e3) {
logger.info(e3.getMessage(), e3);
} catch (IllegalAccessException e4) {
logger.info(e4.getMessage(), e4);
} catch (InvocationTargetException e5) {
logger.info(e5.getMessage(), e5);
} catch (InstantiationException e6) {
logger.info(e6.getMessage(), e6);
}
}
return list;
}
public static String toUpperCase(String word) {
return word.substring(0, 1).toUpperCase() + word.substring(1);
}
最后就可以把工程跑起来了,然后打印出来,
1,one
2,two
3,three
欢迎关注公众号:Java后端技术全栈