java讀取xml檔案

來源:互聯網
上載者:User

第一:寫好檔案為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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.