程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java讀寫XML文件

Java讀寫XML文件

編輯:關於JAVA
 

需要讀取的XML文件:

<?xml version=”1.0″ encoding=”utf-8″?>
<學生花名冊>
<學生 性別 = “男”>
<姓名>李華</姓名>
<年齡>14</年齡>
</學生>
<學生 性別 = “男”>
<姓名>張三</姓名>
<年齡>16</年齡>
</學生>
</學生花名冊>

把該內容拷貝到student.xml中,存放到E盤下即可。


 

XMLDemo.java文件:

  1. import java.io.FileOutputStream;
  2. import java.io.OutputStreamWriter;
  3. import java.io.Writer;
  4. import java.util.ArrayList;
  5. import java.util.Iterator;
  6. import javax.xml.parsers.DocumentBuilder;
  7. import javax.xml.parsers.DocumentBuilderFactory;
  8. import javax.xml.transform.OutputKeys;
  9. import javax.xml.transform.Result;
  10. import javax.xml.transform.Source;
  11. import javax.xml.transform.Transformer;
  12. import javax.xml.transform.TransformerConfigurationException;
  13. import javax.xml.transform.TransformerException;
  14. import javax.xml.transform.TransformerFactory;
  15. import javax.xml.transform.dom.DOMSource;
  16. import javax.xml.transform.stream.StreamResult;
  17. import org.w3c.dom.Document;
  18. import org.w3c.dom.Element;
  19. import org.w3c.dom.Node;
  20. import org.w3c.dom.NodeList;
  21. import org.w3c.dom.Text;
  22. public class XMLDemo {
  23. ArrayList<Student> students_al=null;
  24. private ArrayList<Student> readXMLFile(String file) throws Exception {
  25. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  26. DocumentBuilder builder = dbf.newDocumentBuilder();
  27. Document doc = builder.parse(file); // 獲取到xml文件
  28. // 下面開始讀取
  29. Element root = doc.getDocumentElement(); // 獲取根元素
  30. NodeList students = root.getElementsByTagName(“學生”);
  31. students_al = new ArrayList<Student>();
  32. for (int i = 0; i < students.getLength(); i++) {
  33. // 一次取得每一個學生元素
  34. Element ss = (Element) students.item(i);
  35. // 創建一個學生的實例
  36. Student stu = new Student();
  37. stu.setSex(ss.getAttribute(“性別”));
  38. NodeList names = ss.getElementsByTagName(“姓名”);
  39. Element e = (Element) names.item(0);
  40. Node t = e.getFirstChild();
  41. stu.setName(t.getNodeValue());
  42. NodeList ages = ss.getElementsByTagName(“年齡”);
  43. e = (Element) ages.item(0);
  44. t = e.getFirstChild();
  45. stu.setAge(Integer.parseInt(t.getNodeValue()));
  46. students_al.add(stu);
  47. }
  48. return students_al;
  49. }
  50. // 寫入xml文件
  51. public static void callWriteXmlFile(Document doc, Writer w, String encoding) {
  52. try {
  53. Source source = new DOMSource(doc);
  54. Result result = new StreamResult(w);
  55. Transformer xformer = TransformerFactory.newInstance()
  56. .newTransformer();
  57. xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
  58. xformer.transform(source, result);
  59. } catch (TransformerConfigurationException e) {
  60. e.printStackTrace();
  61. } catch (TransformerException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. private void writeXMLFile(String outfile) {
  66. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  67. DocumentBuilder builder = null;
  68. try {
  69. builder = dbf.newDocumentBuilder();
  70. } catch (Exception e) {
  71. }
  72. Document doc = builder.newDocument();
  73. Element root = doc.createElement(“學生花名冊”);
  74. doc.appendChild(root); // 將根元素添加到文檔上
  75. // 獲取學生信息
  76. for (int i = 0; i < students_al.size(); i++) {
  77. Student s = (Student) students_al.get(i);
  78. // 創建一個學生
  79. Element stu = doc.createElement(“學生”);
  80. stu.setAttribute(“性別”, s.getSex());
  81. root.appendChild(stu);// 添加屬性
  82. // 創建文本姓名節點
  83. Element name = doc.createElement(“姓名”);
  84. stu.appendChild(name);
  85. Text tname = doc.createTextNode(s.getName());
  86. name.appendChild(tname);
  87. // 創建文本年齡節點
  88. Element age = doc.createElement(“年齡”);
  89. stu.appendChild(age); // 將age添加到學生節點上
  90. Text tage = doc.createTextNode(String.valueOf(s.getAge()));
  91. age.appendChild(tage); // 將文本節點放在age節點上
  92. }
  93. try {
  94. FileOutputStream fos = new FileOutputStream(outfile);
  95. OutputStreamWriter outwriter = new OutputStreamWriter(fos);
  96. // ((XmlDocument)doc).write(outwriter); //出錯!
  97. callWriteXmlFile(doc, outwriter, “gbk”);
  98. outwriter.close();
  99. fos.close();
  100. } catch (Exception e) {
  101. e.printStackTrace();
  102. }
  103. }
  104. public static void main(String args[]) {
  105. String str = “E:/student.xml”;
  106. XMLDemo t = new XMLDemo();
  107. try {
  108. ArrayList<Student> al = t.readXMLFile(str);
  109. Iterator<Student> it = al.iterator();
  110. while (it.hasNext()) {
  111. Student s = (Student) it.next();
  112. System.out.println(s.getName() + “\t” + s.getAge() + “\t”
  113. + s.getSex());
  114. }
  115. } catch (Exception e) {
  116. e.printStackTrace();
  117. }
  118. String outfile = “src/stucopy.xml”;
  119. t.writeXMLFile(outfile);
  120. }
  121. }
  122. class Student {
  123. private String sex;
  124. private String name;
  125. private int age;
  126. public int getAge() {
  127. return age;
  128. }
  129. public void setAge(int age) {
  130. this.age = age;
  131. }
  132. public void setSex(String s) {
  133. sex = s;
  134. }
  135. public String getSex() {
  136. return sex;
  137. }
  138. public void setName(String n) {
  139. name = n;
  140. }
  141. public String getName() {
  142. return name;
  143. }
  144. }
 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved