jdom 解析xml

 jdom包下載地址:

http://cloud.github.com/downloads/hunterhacker/jdom/jdom-2.0.4.zip

//

import java.io.FileNotFoundException;   

import java.io.FileOutputStream;   

import java.io.IOException;   

import java.util.List;   

import org.jdom2.Document;   

import org.jdom2.Element;   

import org.jdom2.JDOMException;   

import org.jdom2.input.SAXBuilder;   

import org.jdom2.output.XMLOutputter;   

public class jdom {

public static  void main(String[] args) throws IOException {

parserXml("emoji_china.xml");

}

public static void createXml(String fileName) {   

Document document;   

Element  root;   

root=new Element("employees");   

document=new Document(root);   

Element employee=new Element("employee");   

root.addContent(employee);   

Element name=new Element("name");   

name.setText("ddvip");   

employee.addContent(name);   

Element sex=new Element("sex");   

sex.setText("m");   

employee.addContent(sex);   

Element age=new Element("age");   

age.setText("23");   

employee.addContent(age);   

XMLOutputter XMLOut = new XMLOutputter();   

try {   

XMLOut.output(document, new FileOutputStream(fileName));   

} catch (FileNotFoundException e) {   

e.printStackTrace();   

} catch (IOException e) {   

e.printStackTrace();   

}   

 

}   

 

public static  void parserXml(String fileName) {   

SAXBuilder builder= new SAXBuilder();    

try {   

Document document=builder.build(fileName);   

Element employees=document.getRootElement();    

List<Element> employeeList=employees.getChildren();   

for(int i=0;i<employeeList.size();i++){

Element employee=(Element)employeeList.get(i);

System.out.println(employee.getValue());

List<Element> employeeInfo=employee.getChildren();   

for(int j=0;j<employeeInfo.size();j++){

System.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getValue());

}   

}   

} catch (JDOMException e) {   

e.printStackTrace();   

} catch (IOException e) {   

e.printStackTrace();   

}    

}   

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章