sax 解析xml

前端之家收集整理的这篇文章主要介绍了sax 解析xml前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. package org.sxj.service.product;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import org.sxj.dao.product.ProductDaoImpl;
  7. import org.sxj.model.brand.Brand;
  8. import org.sxj.model.product.Product;
  9. import org.sxj.model.user.User;
  10. import org.xml.sax.Attributes;
  11. import org.xml.sax.SAXException;
  12. import org.xml.sax.helpers.DefaultHandler;
  13.  
  14. public class Sax extends DefaultHandler {
  15.  
  16. private List<Brand> brandList;
  17. private List<User> userList;
  18. private ArrayList<Product> productList;
  19. @Override
  20. public void startDocument() throws SAXException {
  21. productList = new ArrayList<Product>();
  22. }
  23. Product product = null;
  24. String tag = "";
  25. @Override
  26. public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException {
  27. tag = qName;
  28. if (qName.equals("product")) {
  29. product = new Product();
  30. }
  31. }
  32. @Override
  33. public void characters(char[] ch,int start,int length)
  34. throws SAXException {
  35. String data = new String(ch,start,length);
  36. if (tag.equals("productName")) {
  37. product.setName(data+"_");
  38. }
  39. if (tag.equals("productPrice")) {
  40. product.setPrice(Float.parseFloat(data)+100);
  41. }
  42. if (tag.equals("productBrand")) {
  43. for (Brand b : brandList) {
  44. if(b.getBrandName().equals(data)) {
  45. product.setBrand(b.getId());
  46. }
  47. }
  48. product.setName(data);
  49. }
  50. if (tag.equals("productProduceTime")) {
  51. product.setProduceTime(data);
  52. }
  53. if (tag.equals("productPerson")) {
  54. for (User productUser : userList) {
  55. if(productUser.getRealName().equals(data)) {
  56. product.setEnteringPerson(productUser.getId());
  57. }
  58. }
  59. }
  60. tag = "";
  61. }
  62. @Override
  63. public void endElement(String uri,String qName)
  64. throws SAXException {
  65. if (qName.equals("product")) {
  66. productList.add(product);
  67. }
  68. }
  69. public Sax(List<Brand> list1,List<User> list2) {
  70. brandList = list1;
  71. userList = list2;
  72. }
  73. @Override
  74. public void endDocument() throws SAXException {
  75. }
  76.  
  77. public List<User> getUserList() {
  78. return userList;
  79. }
  80.  
  81. public void setUserList(List<User> userList) {
  82. this.userList = userList;
  83. }
  84.  
  85. public List<Brand> getBrandList() {
  86. return brandList;
  87. }
  88.  
  89. public void setBrandList(List<Brand> brandList) {
  90. this.brandList = brandList;
  91. }
  92.  
  93. public ArrayList<Product> getProductList() {
  94. return productList;
  95. }
  96.  
  97. public void setProductList(ArrayList<Product> productList) {
  98. this.productList = productList;
  99. }
  100.  
  101. }

猜你在找的XML相关文章