【JAVA WEB】學習筆記——XML解析

  1. 解析方式:

    • DOM解析
      直接性把XML文檔全部讀取到內存中來,會得到一個Document對象,然後對其訪問操作,DOM方式W3C推薦的一種方式
      (好處:增刪改查方便)
    • SAX解析
      Simple API for XML,不是官方的標準,但他是XML領域事實上的標準
      SAX是邊讀取XML文檔,邊解析
  2. XML的解析器

    • Crimson(SUN)
    • Xerces(IBM -> Apache)
    • Aelfred(JDOM, DOM4J)
    • 第三方解析工具 JDOM,DOM4J(常用)
  3. Java裏面對XML的解析工具JAXP
    JAXP方式解析XML步驟:

 //獲取 DocumentBuilderFactory 實例
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//加載要解析的XML文檔,獲取Document對象
Document doc = db.parse(new FileInputStream("xmlfile/students.xml"));
//對Document對象進行操作
//動態生成xml文檔,並寫入文件
//獲取DocumentBuilderFactory實例
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInsatence();
//通過Factory獲取DocumentBuilder解析器對象實例
DocumentBuilder db = dbf.newDocumentBuilder();
//創建一個新的Document對象
Document doc = db.newDocument();
//添加一系列的元素
Element rootElt = doc.createElement("班級");

Element studentElt1 = doc.createElement("學生");

Element studentElt1 = doc.createElement("姓名");
studentElt1_name.setTextContent("張曼玉");
studentElt1_name.setAttribute("別名","玉姐");

Element studentElt1_sex = doc.createElement("姓名");
studentElt1_sex.setTextContent("女");

studentElt1.appendChild(studentElt1_name);
studentElt1.appendChild(studentElt1_sex);

Element studentElt2 = doc.createElement("學生");

Element studentElt2_name = doc.createElement("姓名");
studentElt2_name.setTextContent("林青霞");
studentElt2_name.setAtribute("別名","霞妹");

Element studentElt2_sex = doc.createElement("性別");
studentElt2_sex.setTextContent("女");

studentElt1.appendChild(studentElt1_name);
studentElt1.appendChild(studentElt1_sex);

rootElt.appendChild(studentElt1);
rootElt.appendChild(studentElt2);

doc.appendChild(rootElt);

//獲取TransfomerFactory實例
TransformerFatory tff = TransformerFactory.newInstance();
//通過TransfomerFactory創建Transformer實例
Transformer tf = tff.newTransformer();
//通過Document生成DOMSource實例
DOMSource sourse = new DOMSource(doc);
//創建寫DOM文檔的輸出流
StreamResult xmlResult = new StreamResult(new FileOutputStream("test.xml"));
//通過Transfomer的transform方法把DOMSource對象寫入輸出流
tf.transform(source,xmlResult);
  1. JAXP方式解析XML步驟(SAX方式)
    SAX解析XML步驟
SAXPerserFactory spf = ASXPerserFactory.newInstance();
ASXParser sp = spf.newSAXParser();
sp.parse("test.xml",new MyHandler() );
  1. SAX主要用於對XML文檔解析,不能去修改、刪除、添加元素
    SAX是推行機制,把發現的內容告訴程序員(函數),程序員可以自己下決定如何處理
    MyHandler接口:
    DefaultHandler SAX事件:
    • startDoucment()
      發現文檔的開始,解析器開始掃描文件
    • endDocument()
      發現了文檔尾
    • startElement()
      發現了一個起始標籤,返回元素名,以及所有屬性名和值
    • character()
      發現了一些文本,將得到一個字符數組,該字符數組的偏移量和長度變量,由這三個變量可以得到解析器發現的文本
    • endElement()
      發現一個結束標籤,並返回元素名稱

DOM4J解析XML

被解析的XML:

<?xml version="1.0" encoding="UTF-8"?>

<學生們>
    <學生>
        <學號>04142122</學號>
        <姓名>張三</姓名>
    </學生>
    <學生>
        <學號>04142138</學號>
        <姓名>李四</姓名>
    </學生>
    <學生>
        <學號>04156700</學號>
        <姓名>王五</姓名>
    </學生>
    <學生 學號="04149441" 姓名="馬六" />
</學生們>

JAVA代碼(引入dom4j-1.6.1包):

public class TestDOM4JParseXML {

    public static void main(String[] args) throws DocumentException {

        SAXReader reader = new SAXReader();
        FileInputStream fis = null;

        try {
            fis = new FileInputStream("XMLDemo02.xml");
            Document doc = reader.read(fis);

            //獲取根元素
            Element rootElt = doc.getRootElement();
            System.out.println(rootElt.getName());
            List elements = rootElt.elements();
            System.out.println(elements.size());
            for(int i=0 ; i<elements.size();i++){
                Element elt = (Element)elements.get(i);
                System.out.println(elt.getName());
                List attrList = elt.attributes();
                for(int j=0 ; j<attrList.size() ; j++){
                    Attribute attr = (Attribute) attrList.get(j);
                    System.out.println("\t屬性" + attr.getName() + " = " + attr.getValue());
                }
                List subEltList = elt.elements();
                for(int j=0 ; j<subEltList.size(); ++j){
                    Element subElt = (Element) subEltList.get(j);
                    System.out.println("\t子元素" + subElt.getName() + " : " + subElt.getText());
                }
            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

結果:

學生們
4
學生
    子元素學號 : 04142122
    子元素姓名 : 張三
學生
    子元素學號 : 04142138
    子元素姓名 : 李四
學生
    子元素學號 : 04156700
    子元素姓名 : 王五
學生
    屬性學號 = 04149441
    屬性姓名 = 馬六

遞歸解析XML

待解析xml

<?xml version="1.0" encoding="UTF-8"?>
<stuents id="123">
    <student>
        <name length="12">張三</name>
    </student>
    <student>
        <name length="12">李四</name>
    </student>
</stuents>

java代碼:

public class TestDOM4JParseXML {
    public static void main(String[] args) {
        SAXReader reader = new SAXReader();
        FileInputStream fis = null;

        try {
            fis = new FileInputStream("XMLDemo01.xml");

            Document doc = reader.read(fis);
            Element rootElt = doc.getRootElement();
            printElementDetail(rootElt,"");
        } catch (FileNotFoundException | DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                if(fis != null){
                    fis.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void printElementDetail(Element elt,String str){
        System.out.print(str + elt.getName());
        List<Attribute> attrList = elt.attributes();
        int attrCount = attrList.size();
        if(attrList.size() != 0){
            System.out.print("[");
            for(int i=0 ; i<attrList.size() ; ++i){
                Attribute attr = attrList.get(i);
                System.out.print(attr.getName()+" = "+attr.getValue());
                if(i < attrCount - 1){
                    System.out.print(", ");
                }
            }
            System.out.print("]");
        }
        String text = elt.getText().trim();
        if(!"".equals(text)){
            System.out.print(": "+text);
        }
        System.out.println();
        List<Element> eltList = elt.elements();
        for(int i=0 ;i<eltList.size() ; ++i){
            Element subElt = eltList.get(i);
            printElementDetail(subElt,str + "\t");
        }
    }
}

結果:

stuents[id = 123]
    student
        name[length = 12]: 張三
    student
        name[length = 12]: 李四

生成XML

public class DOM4JCreateXML {
    /**
     * 目標XML:
     * <select name="city">
     *      <option value="1">北京市</option>
     *      <option value="2">天津市</option>      
     *      <option value="3">上海市</option>
     *      <option value="4">重慶市</option>
     * </select>
     */
    public static void main(String[] args) {
        //創建Document
        Document doc = DocumentHelper.createDocument();
        Element rootElt = doc.addElement("select");
        rootElt.addAttribute("name", "city");

        Element cityElt1 = rootElt.addElement("option");
        cityElt1.addAttribute("value", "1");
        cityElt1.addText("北京市");

        Element cityElt2 = rootElt.addElement("option");
        cityElt2.addAttribute("value", "2");
        cityElt2.addText("天津市");

        Element cityElt3 = rootElt.addElement("option");
        cityElt3.addAttribute("value", "3");
        cityElt3.addText("上海市");

        Element cityElt4 = rootElt.addElement("option");
        cityElt4.addAttribute("value", "4");
        cityElt4.addText("重慶市");


        XMLWriter writer = null;
        FileWriter fw = null;
        try {
            fw = new FileWriter("city.xml");
            //doc.write(fw);難以控制格式
            OutputFormat format = OutputFormat.createPrettyPrint();

            writer = new XMLWriter(fw,format);
            writer.write(doc);
            System.out.println("寫入成功!");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                if(fw!=null){
                    fw.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章