课题打卡,请老师检查有无疏漏。

课题打卡,请老师检查有无疏漏。

package mgallery.utils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import mgallery.entity.Painting;

//将xml对象解析为java对象
public class XmlDataSource {
//通过static关键字保证全局唯一
    private static List data = new ArrayList();
    private static String dataFile;
    static { 
      //在程序运行以后得到类路径目录下的painint.xml的路径地址
       dataFile =  XmlDataSource.class.getResource("/painting.xml").getPath();
       //System.out.println(dataFile);
       //倘若上面读取到的路径包含有特殊字符,类似于空格,
       //会被自动转换为%20,导致读取时出错,底下为解决方法
       reload();
    }
    
     private static void reload() {
       URLDecoder decode = new URLDecoder();
       try {
        dataFile = decode.decode(dataFile,"UTF-8");
        //利用dom4j对xml文档进行解析
        SAXReader reader = new SAXReader();
        //1.获取Document对象
        Document document = reader.read(dataFile);
        //2.利用xpath得到xml节点集合,导入一定是org.dom4j.node
        List<Node> nodes = document.selectNodes("/root/painting");
        data.clear();
        for (Node node:nodes) {
          Element element = (Element)node;
          String id = element.attributeValue("id");
          String pname = element.elementText("pname");
          Painting painting = new Painting();
          painting.setId(Integer.parseInt(id));
          painting.setPname(pname);
          painting.setCategroy(Integer.parseInt(element.elementText("category")));
          painting.setPrice(Integer.parseInt(element.elementText("price")));
          painting.setPreview(element.elementText("preview"));
          painting.setDescrption(element.elementText("description"));
          data.add(painting);
        }
      } catch (UnsupportedEncodingException | DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
       
    }
     
    
    public static List<Painting> getRawData(){
      return data;
    }
    
    public static void append(Painting painting) {
        SAXReader reader = new SAXReader();
        Writer writer = null;
        try {
          Document document = reader.read(dataFile);
          Element root = document.getRootElement();
          Element p = root.addElement("painting");
          p.addAttribute("id", String.valueOf(data.size()+1));
          p.addElement("pname").setText(painting.getPname());
          p.addElement("category").setText(painting.getCategroy().toString());
          p.addElement("price").setText(painting.getPrice().toString());
          p.addElement("preview").setText(painting.getPreview());
          p.addElement("description").setText(painting.getDescrption());
          writer = new OutputStreamWriter(new FileOutputStream(dataFile),"UTF-8");
          System.out.println(dataFile);
          document.write(writer);
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }finally {
          if(writer != null) {
            try {
              writer.close();
            } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
          reload();
        }
    }
    
    
    public static void update(Painting painting) {
      SAXReader reader = new SAXReader();
      Writer writer = null;
      try {
        Document document =reader.read(dataFile);
        List<Node> nodes = document.selectNodes("/root/painting[@id="+ painting.getId()+"]");
        if(nodes.size() == 0) {
          throw new RuntimeException("id: " + painting.getId() + "不存在");
        }
        Element p = (Element)nodes.get(0);
        p.selectSingleNode("pname").setText(painting.getPname());
        p.selectSingleNode("category").setText(painting.getCategroy().toString());
        p.selectSingleNode("price").setText(painting.getPrice().toString());
        p.selectSingleNode("description").setText(painting.getDescrption());
        p.selectSingleNode("preview").setText(painting.getPreview());
        writer = new OutputStreamWriter(new FileOutputStream(dataFile),"UTF-8");
        document.write(writer);
        
      } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }finally {
        if(writer != null) {
          try {
            writer.close();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        reload();
      }
      
    }
    
    
    public static void delete(Painting painting) {
      SAXReader reader = new SAXReader();
      Writer writer = null;
      Document document;
      try {
        document = reader.read(dataFile);
        List<Node> nodes = document.selectNodes("/root/painting[@id="+ painting.getId()+"]");

        if(nodes.size() == 0) {
          throw new RuntimeException("id: " + painting.getId() + "不存在");
        }
        
        Element p =(Element)nodes.get(0);
        Element r = p.getParent();
        r.remove(p);
        writer = new OutputStreamWriter( new FileOutputStream(dataFile),"UTF-8");
        document.write(writer);
        
      } catch (DocumentException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }finally{
        if(writer != null) {
          try {
            writer.close();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        reload();
      }

      
    }

        
    public static void main(String[] args) {
      Painting p = new Painting();
      p.setPname("测试油画");
      p.setId(2);
      p.setCategroy(1);
      p.setPrice(4000);
      p.setPreview("/upload/1.jpg");
      p.setDescrption("描述信息");
      XmlDataSource.delete(p);
    }
  
}


正在回答

登陆购买课程后可参与讨论,去登陆

1回答

已完成练习,继续加油!
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师