首页 > 代码库 > XML文件(1)--使用DOM示例

XML文件(1)--使用DOM示例

  •     其他依赖字段/方法
  1. // 书籍列表
  2. private List<Book> bookList = new LinkedList<Book>();
  3. /**
  4. * 根据xml文件,得到书籍列表
  5. *
  6. * @param file
  7. * @return
  8. */
  9. public List<Book> getBookList(String file) {
  10. parseXML(file);
  11. return bookList;
  12. }
  • 获取DocumentBuilder(文件解析器)
  1. /**
  2. * 获取DocumentBuilder对象
  3. *@return
  4. */
  5. private DocumentBuilder getDocumentBuilder() {
  6. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  7. DocumentBuilder builder = null;
  8. try {
  9. builder = factory.newDocumentBuilder();
  10. } catch (ParserConfigurationException e) {
  11. // TODO Auto-generated catch block
  12. e.printStackTrace();
  13. }
  14. return builder;
  15. }

  • 解析XML文件
  1. /**
  2. * 读取XML,并将book对象存入书籍列表
  3. *
  4. * @param file
  5. */
  6. private void parseXML(String file) {
  7. // 1.临时书籍变量
  8. Book book;
  9. try {
  10. // 2.获取DocumentBuilder对象
  11. DocumentBuilder documentBuilder = getDocumentBuilder();
  12. // 3.加载XML文件到当前项目下,获取Document‘文档’对象
  13. Document document = documentBuilder.parse(file);
  14. // 4.获取节点名称是book的集合
  15. NodeList books = document.getElementsByTagName("book");
  16. // 5.遍历book节点集合
  17. for (int i = 0; i < books.getLength(); i++) {
  18. // 重置book变量
  19. book = new Book();
  20. // 5.1声明book节点变量
  21. Node bookNode = books.item(i);
  22. // 5.2获取book节点的属性集合
  23. NamedNodeMap nodeMap = bookNode.getAttributes();
  24. // 5.3遍历属性集合,判断并为book对象的属性赋值
  25. for (int j = 0; j < nodeMap.getLength(); j++) {
  26. // 5.4声明book的属性
  27. Node attrNode = nodeMap.item(j);
  28. // 5.5如果属性Name为id
  29. if (attrNode.getNodeName().equals("id")) {
  30. book.setId(Integer.valueOf(attrNode.getNodeValue()));
  31. }
  32. }
  33. // 5.6获取book节点的子节点
  34. NodeList childList = bookNode.getChildNodes();
  35. // 5.7遍历子节点
  36. for (int j = 0; j < childList.getLength(); j++) {
  37. // 5.8 声明book子节点
  38. Node child = childList.item(j);
  39. // 判断是否是节点。NodeType有三种:
  40. // Element(节点):1,Attribute(属性):2,#Text(文本):3。
  41. if (Node.ELEMENT_NODE == child.getNodeType()) {
  42. // 5.9使用switch case判断,并为book对象属性赋值
  43. switch (child.getNodeName()) {
  44. case "title":
  45. book.setTitle(child.getTextContent());
  46. break;
  47. case "author":
  48. book.setAuthor(child.getTextContent());
  49. break;
  50. case "price":
  51. book.setPrice(Double.valueOf(child.getTextContent()));
  52. break;
  53. case "year":
  54. book.setYear(child.getTextContent());
  55. break;
  56. case "language":
  57. book.setLanguage(child.getTextContent());
  58. break;
  59. default:
  60. System.out.println("未知属性!");
  61. }
  62. }
  63. }
  64. // 6 将book对象放入集合
  65. bookList.add(book);
  66. }
  67. } catch (SAXException e) {
  68. // TODO Auto-generated catch block
  69. e.printStackTrace();
  70. } catch (IOException e) {
  71. // TODO Auto-generated catch block
  72. e.printStackTrace();
  73. }
  74. }

  • 生成XML文件
  1. /**
  2. * 生成XML文件,写入book列表
  3. *
  4. * @param file
  5. */
  6. private void createXML(List<Book> bookList, String file, String encoding) {
  7. DocumentBuilder builder = getDocumentBuilder();
  8. //创建document文件
  9. Document document = builder.newDocument();
  10. // 在document中,创建根节点
  11. Element eBookstore = document.createElement("bookstore");
  12. for (Book book : bookList) {
  13. // 创建book节点
  14. Element eBook = document.createElement("book");
  15. // 为book节点添加id属性
  16. eBook.setAttribute("id", String.valueOf(book.getId()));
  17. // 创建book的子节点
  18. Element eTitle = document.createElement("title");
  19. // 创建CDATA元素
  20. CDATASection titleByCDATA = document.createCDATASection(book.getTitle());
  21. // 将CDATA元素加入title
  22. eTitle.appendChild(titleByCDATA);
  23. eTitle.setTextContent(book.getTitle());
  24. Element eAuthor = document.createElement("author");
  25. eAuthor.setTextContent(book.getAuthor());
  26. Element eYear = document.createElement("year");
  27. eYear.setTextContent(book.getYear());
  28. Element ePrice = document.createElement("price");
  29. ePrice.setTextContent(String.valueOf(book.getPrice()));
  30. Element eLanguage = document.createElement("language");
  31. eLanguage.setTextContent(book.getLanguage());
  32. // 将子节点添加到book中
  33. eBook.appendChild(eTitle);
  34. eBook.appendChild(eAuthor);
  35. eBook.appendChild(eYear);
  36. eBook.appendChild(ePrice);
  37. eBook.appendChild(eLanguage);
  38. // 将book节点添加到bookstore根节点中
  39. eBookstore.appendChild(eBook);
  40. }
  41. // 将bookstore节点添加到document中,目前文件只存在与内存中
  42. document.appendChild(eBookstore);
  43. // 创建TransformerFactory 对象
  44. Transformer former = getTransformer(encoding);
  45. try {
  46. // 创建输出流
  47. OutputStream output = new FileOutputStream(file);
  48. // 输出XML文件到硬盘
  49. former.transform(new DOMSource(document), new StreamResult(output));
  50. } catch (TransformerConfigurationException e) {
  51. // TODO Auto-generated catch block
  52. e.printStackTrace();
  53. } catch (FileNotFoundException e) {
  54. // TODO Auto-generated catch block
  55. e.printStackTrace();
  56. } catch (TransformerException e) {
  57. // TODO Auto-generated catch block
  58. e.printStackTrace();
  59. }
  60. }

  • 保存Tranformer对象,用于保存XML文件,设置自动换行和编码
  1. /**
  2. * 获取Tranformer对象
  3. *
  4. * @param encoding
  5. * 指定编码
  6. * @return Tranformer
  7. */
  8. private Transformer getTransformer(String encoding) {
  9. // 创建TransformerFactory 对象
  10. TransformerFactory factory = TransformerFactory.newInstance();
  11. Transformer former = null;
  12. try {
  13. former = factory.newTransformer();
  14. // 换行
  15. former.setOutputProperty(OutputKeys.INDENT, "yes");
  16. // 指定编码
  17. former.setOutputProperty(OutputKeys.ENCODING, encoding);
  18. } catch (TransformerConfigurationException e) {
  19. // TODO Auto-generated catch block
  20. e.printStackTrace();
  21. }
  22. return former;
  23. }

XML文件(1)--使用DOM示例