java学习笔记:使用dom4j解析xml
2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
最近寫程序需要用java解析xml文件,于是在網(wǎng)上借鑒了一下“殘缺的孤獨”的博客,使用了dom4j方法。
?
xml格式如下:
解析的核心代碼:
@SuppressWarnings({ "unchecked", "rawtypes" }) public Proposal parseXml(String xmlPath) throws IOException{ Proposal proposal=new Proposal(); File Xml=new File(xmlPath); SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read(Xml); //讀取文件,轉(zhuǎn)化為Document Element root = document.getRootElement();//獲取xml的根節(jié)點 List<Element> elementList = root.elements();//獲取根節(jié)點之下的各子節(jié)點 for (Element e : elementList) {//foreach遍歷 //title if(e.elementText("AwardTitle")!=null){ if(!e.elementText("AwardTitle").equals("")) proposal.setTitle(e.elementText("AwardTitle").replaceAll("& ","").trim()); System.out.println("title:"+proposal.getTitle()); } //awarded_amount if(e.elementText("AwardAmount")!=null){ if(!e.elementText("AwardAmount").equals("")) proposal.setAwarded_amount(e.elementText("AwardAmount").trim()); System.out.println("awarded_amount:"+proposal.getAwarded_amount()); } //nsf_directorate Element Organization=e.element("Organization"); if(Organization!=null){ Element Directorate=Organization.element("Directorate"); if(Directorate!=null){ if(Directorate.elementText("LongName")!=null){ if(!Directorate.elementText("LongName").equals("")) proposal.setNsf_directorate(Directorate.elementText("LongName").replaceAll("& ", "").trim()); System.out.println("nsf_directorate:"+proposal.getNsf_directorate()); } } } } //program_element_code List<String> Listprogram_element_code=new ArrayList(); List<Element> ListProgramElement=new ArrayList(); ListProgramElement=e.elements("ProgramElement"); for(Element ProgramElement:ListProgramElement){ System.out.println("program_element_code:"+ProgramElement.elementText("Code").trim()); Listprogram_element_code.add(ProgramElement.elementText("Code").trim()); } if(Listprogram_element_code.size()!=0) proposal.setProgram_element_code(Listprogram_element_code); }catch (DocumentException e) { System.out.println(e.getMessage()); } return proposal; }其中該xml的根節(jié)點即為award,AwardTitle、AwardAmount等均為根節(jié)點之下的子節(jié)點。
先介紹一下e.elementText()、e.element()、e.elements()三種方法的區(qū)別:e.elementText("AwardTitle")返回的是以AwardTitle為名的節(jié)點的文本的值,返回的類型是String;e.element("Organization")返回的是以O(shè)rganization為名的結(jié)點,返回類型為Element;e.elements(“ProgramElement”)返回的是以ProgramElement為名的所有節(jié)點(即有多個同名節(jié)點時使用該方法),返回類型為List。
像AwardTitle、AwardAmount一般的節(jié)點,使用e.elementText()方法即可;像Value這種子節(jié)點,需要先使用e.element()方法獲得Organization節(jié)點,之后e.elementText()返回文本部分;而像ProgramElement有多個,需要定義一個List,使用e.elements()方法。
?
特別注意:在寫程序過程中,我還遇到空指針NullPointerException異常,原因是當(dāng)該節(jié)點不存在時,找不到該節(jié)點,則會報空指針異常錯誤。我解決的辦法是在將數(shù)據(jù)set到數(shù)據(jù)庫之前加了判斷語句?if(e.elementText("AwardTitle")!=null)。
?
轉(zhuǎn)載于:https://my.oschina.net/u/2619218/blog/626160
總結(jié)
以上是生活随笔為你收集整理的java学习笔记:使用dom4j解析xml的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nginx安装及编译参数详解
- 下一篇: oracle中避免sort操作