1. 程式人生 > 實用技巧 >xml的增刪查 dom的增改查 複雜註釋

xml的增刪查 dom的增改查 複雜註釋

xml的增刪查


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class Ttest {
    public static void main(String[] args) {
        Ttest test = new Ttest();
        test.getDom(); //基礎 獲取Dom
//        test.select();
//        test.add();
        test.delete();
        test.writer("2.xml");
//        test.delete();  必須放在 writer 的前面,否則無作用

    }

    private Document doc;

//查詢
    public void select() {
        NodeList nodeBrandList = doc.getElementsByTagName("Brand");
        for (int i = 0; i < nodeBrandList.getLength(); i++) {
            Node nodeBrand = nodeBrandList.item(i);
            Element elementBrand = (Element) nodeBrand;
            System.out.println(elementBrand.getAttribute("name"));

            NodeList nodeLisType = elementBrand.getChildNodes();
            for (int j = 0; j < nodeLisType.getLength(); j++) {
                Node nodeType = nodeLisType.item(j);
                if (nodeType.getNodeType() == Element.ELEMENT_NODE) {
                    Element elementType = (Element) nodeType;
                    System.out.println(elementType.getAttribute("name"));
                }
            }

        }


    }

    public void getDom() {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(new File("src/收藏資訊.xml"));
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
//新增
    public void add() {
        Element elementBrand = doc.createElement("Brand"); //新增Brand節點
        elementBrand.setAttribute("name", "OPPO");  //用 setAttribute ,新增 name="OPPO"
        Element elementType = doc.createElement("Type");  //新增Brand節點
        elementType.setAttribute("name", "r200");  //用 setAttribute ,新增
        elementBrand.appendChild(elementType);
        doc.getElementsByTagName("PhoneInfo").item(0).appendChild(elementBrand); //將新增的置於 PhoneInfo 標籤內
    }
//寫入
    public void writer(String path) {
        try {
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult sr = new StreamResult(new OutputStreamWriter(new FileOutputStream(path), "utf-8"));
            tf.transform(source, sr);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
//刪除
    public void delete() {
        NodeList nodeBrandList = doc.getElementsByTagName("Brand");
        for (int i = 0; i < nodeBrandList.getLength(); i++) {
            Node nodeBrand = nodeBrandList.item(i);
//            轉換屬性節點
            Element elementBrand = (Element) nodeBrand;
            if (elementBrand.getAttribute("name").equals("蘋果")) {
                elementBrand.getParentNode().removeChild(elementBrand);
            }
        }
    }
}

dom的增改查


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import javax.servlet.http.HttpServlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

public class Test1 extends HttpServlet {
    public static void main(String[] args) throws IOException {
        Test1 test1 = new Test1();
        test1.getDoc();
//        test1.select(); // 依賴 getDoc ,才可以用 select
//        test1.add();  // 依賴 getDoc ,才可以用 select
        test1.update();
        test1.writer("4.xml");
    }

    private Document doc;
    //xml 轉換成 dom
    private void getDoc (){
        try {
            SAXReader sr = new SAXReader();
            doc = sr.read(new File("src/收藏資訊.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public void select(){
        Element elementRoot = doc.getRootElement();
        Iterator<Element> iterator = elementRoot.elementIterator();
        while (iterator.hasNext()){
            Element elementBrand = iterator.next();
            System.out.println(elementBrand.attributeValue("name"));
            for (Iterator<Element>iterator1 = elementBrand.elementIterator();iterator1.hasNext();){
                Element elementType = iterator1.next();
                System.out.println(elementType.attributeValue("name"));
            }
         }
    }
//    新增
    public void add() {
        Element elementRoot = doc.getRootElement();
        Element elementBrand = elementRoot.addElement("Brand");
        elementBrand.addAttribute("name", "OPPO");
        Element elementType = elementRoot.addElement("Type");
        elementType.addAttribute("name", "豪華");
    }

//    寫入
    public void writer(String path) throws IOException {
        FileOutputStream fis = new FileOutputStream(path);
        OutputFormat out = OutputFormat.createPrettyPrint();
        out.setEncoding("utf-8");

        XMLWriter writer = new XMLWriter(fis,out);
        writer.write(doc);
    }

//    刪除
    public void update(){
        int num = 1;
        Element elementRoot = doc.getRootElement();
        Iterator<Element> iterator = elementRoot.elementIterator();
        while (iterator.hasNext()){
            Element elementBrand = iterator.next();
            elementBrand.addAttribute("id",num+"");
            num++;
        }
    }

}

複雜註釋


import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

//複雜註釋
@WebServlet(name="servletConfig",urlPatterns = "/dd",loadOnStartup = 0,  //一定帶斜杆
        initParams = {@WebInitParam(name="aaa",value = "ddd"),
                @WebInitParam(name="name",value = "admin"),
                @WebInitParam(name="kk",value = "www")
                                                        })

public class ServletConfig extends HttpServlet {
    
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        config配置
        Enumeration<String> enume = this.getServletConfig().getInitParameterNames();
     while (enume.hasMoreElements()){
            String key = enume.nextElement();
            System.out.println(key+"\t"+this.getServletConfig().getInitParameter(key));
        }

    }
}