1. 程式人生 > >dom4j 解析 XML

dom4j 解析 XML

匯入dom4j.jar包

  該包需要你去下載。

  建立xml檔案

  XMLWriter writer = null;// 宣告寫XML的物件

  OutputFormat format =

  OutputFormat.createPrettyPrint();

  format.setEncoding("utf-8");// 設定XML檔案的編碼格式

  String filePath = "F://student.xml";//儲存xml檔案路徑

  File file = new File(filePath);

  Document _document = DocumentHelper.createDocument();

  Element _root = _document.addElement("學生資訊");//----------根

  Element student = _root.addElement("學生");

  Element _id = student.addElement("編號");

  _id.setText("001");

  Element _name = student.addElement("姓名");

  _name.setText("灰機");

  Element _age = student.addElement("年齡");

  _age.setText("18");

  for(int i=0;i<5;i++) {

  Element _student = _root.addElement("record");

  _student.addAttribute("sid", "00"+i);

  _student.addAttribute("phone", "1100"+i);

  }

  try

  {

  writer = new XMLWriter(new FileWriter(file), format);

  writer.write(_document);

  writer.close();

  } catch (IOException e) {

  e.printStackTrace();

  }

  System.out.println("操作結束! ");

  生成結果圖:

  

  讀取xml檔案

  SAXReader reader = new SAXReader();

  String filePath = "f://student.xml";

  File file = new File(filePath);

  Document document;

  try {

  document = reader.read(file);

  Element root = document.getRootElement();// 得到根節點

  /*Element database = (Element)root.selectSingleNode("//學生資訊/學生");

  List list = database.elements(); //得到database元素下的子元素集合

  for(Object obj:list){

  Element element = (Element)obj;

  //getName()是元素名,getText()是元素值

  System.out.println(element.getName()+": "+element.getText());

  }*/

  List nodes = root.elements("學生");

  for (Iterator it = nodes.iterator(); it.hasNext();) {

  Element elm = (Element) it.next();

  for(Iterator it2=elm.elementIterator();it2.hasNext();){

  Element elel=(Element)it2.next();

  System.out.println(elel.getName()+":"+elel.getText()+":");

  }

  }

  for (Iterator i = root.elementIterator("record"); i.hasNext();) //對所有record子節點進行遍歷

  {

  Element student = (Element) i.next();

  //if (student.attributeValue("sid").equals("001")) //如果record屬性sid的值等於001

  for(Iterator it= student.attributeIterator();it.hasNext();)//獲取record節點的所有屬性

  {

  Attribute attribute = (Attribute) it.next();

  String name=attribute.getName();//獲取屬性名

  String text=attribute.getText();//獲取屬性值

  System.out.println(name + " :"+text);

  }

  }

  } catch (DocumentException e) {

  e.printStackTrace();

  }

  本篇文件便於可讀,所以採用對照式編碼格式。