---
title: "XML解析"
author: "easay107"
date: "2012-05-21T17:29:22Z"
tags: []
categories: ["企业架构"]
slug: "xml"
draft: false
lastmod: "2012-05-21T17:29:22Z"
id: 1536486
url: "https://easay107.iteye.com/blog/1536486"
---

解析XML有两种方式

方式一：Dom解析器：

1，读取XML文件中的内容

        //读取XML文件中的内容

       

        //创建一个公司

        DocumentBuilderFactory factory=DocumentBuilderFactory.*newInstance*();

        //创建队伍

        DocumentBuilder bui=factory.newDocumentBuilder();

        //获取资源（即你要去哪儿读取数据）

        Class c=Class.*forName*("ReadXML");//forName（本类的名称）

        InputStream in=c.getResourceAsStream("Stu.xml");

        //创建树

        Document doc= bui.parse(in);

        in.close();

       

        //取出&lt;stu&gt;节点

        NodeList nodes=doc.getElementsByTagName("stu");

        **for**(**int** i=0;i&lt;nodes.getLength();i++){

            //取出&lt;stu&gt;节点的id属性值

            Element e=(Element)nodes.item(i);

            String id=e.getAttribute("id");

           

            //根据&lt;stu&gt;节点取到&lt;stu&gt;节点下的&lt;name&gt;节点

            NodeList nodeList=e.getElementsByTagName("name");

            //取出&lt;name&gt;节点下的值

            Element el=(Element)nodeList.item(0);

            String name=el.getTextContent();

    2，往XMl中写入信息

                //创建公司

        DocumentBuilderFactory factory=DocumentBuilderFactory.*newInstance*();

        //创建队伍

        DocumentBuilder bui=factory.newDocumentBuilder();

        //创建文档对象

        Document doc=bui.newDocument();

        //设置版本

        doc.setXmlVersion("1.0");

       

        //写入根节点

        Element root=doc.createElement("teacher");

        doc.appendChild(root);

        Scanner input=**new** Scanner(System.*in*);

        **for**(**int** i=0;i&lt;3;i++){

            //创建&lt;tea&gt;节点

            Element tea=doc.createElement("tea");

            System.*out*.println("请输入老师的编号：");

            String id=input.next();

            tea.setAttribute("id", id);

           

            //加入属性和&lt;name&gt;节点

            Element name=doc.createElement("name");

            System.*out*.println("请输入老师的姓名：");

            String n=input.next();

            name.setTextContent(n);

           

            tea.appendChild(name);

            root.appendChild(tea);

        }

        //保存XML文件也可调用SaveXML（）方法

       

        TransformerFactory fac=TransformerFactory.*newInstance*();

        Transformer tf=fac.newTransformer();

       

        DOMSource source=**new** DOMSource(doc);

        StreamResult result=**new** StreamResult("f:/teas.xml");

       

        tf.transform(source, result);

3，修改XMl中的信息

            //调用得到DOC的方法

        Document doc=getDoc();

       

         NodeList nodeList=doc.getElementsByTagName("tea");

        **for**(**int** i=0;i&lt;nodeList.getLength();i++){

            Element el=(Element)nodeList.item(i);

           

            String id=el.getAttribute("id");

            **if**(id.equals(tea.getId())){

                NodeList nodes=el.getElementsByTagName("name");

                Element name=(Element)nodes.item(0);

                name.setTextContent(tea.getName());

                **break**;

            }

        }

       

        //调用保存的方法

        SaveXML(doc);

private static final String *FILE*="f:/teas.xml"; 

//得到DOM的方法

    **public** Document getDoc() **throws** ParserConfigurationException, SAXException,

            IOException {

        DocumentBuilderFactory factory=DocumentBuilderFactory.*newInstance*();

        DocumentBuilder bui=factory.newDocumentBuilder();

       

        Document doc=bui.parse(*FILE*);

        **return** doc;

    }

 

//保存XML文件的方法

    **private** **void** SaveXML(Document doc)

            **throws** TransformerFactoryConfigurationError,

            TransformerConfigurationException, TransformerException {

        TransformerFactory factory=TransformerFactory.*newInstance*();

        Transformer tf=factory.newTransformer();

       

        DOMSource source=**new** DOMSource(doc);

        StreamResult result=**new** StreamResult(*FILE*);

       

        tf.transform(source, result);

    }

 

3，删除XMl中的信息

      //删除方法

    **public** **void** deleteInfo(String id)**throws** Exception{

        Document doc=getDoc();

       

        doc.getDocumentElement();

       

        NodeList list=doc.getElementsByTagName("tea");

        **for**(**int** i=0;i&lt;list.getLength();i++){

            Element el=(Element)list.item(i);

            String ids=el.getAttribute("id");

            **if**(ids.equals(id)){

                Element root=doc.getDocumentElement();

                root.removeChild(el);

               

                **break**;

            }

        }

        SaveXML(doc);

    }

方式二：SAX解析器：

      继承：DefaultHandler

      实现其五个方法：

       //文档开始了

   **public** **void** startDocument() **throws** SAXException {

      System.*out*.println("文档开始了");

   }

   //文档结束了

   **public** **void** endDocument() **throws** SAXException {

      System.*out*.println("文档结束了");

   }

    //元素开始了

   **public** **void** startElement(String uri, String localName, String  

                   name,Attributes attributes) **throws** SAXException {

      **if**(name.equals("tea")){

         System.*out*.println("id:" + attributes.getValue("id"));

      }

   }

   //文本开始了

   **public** **void** characters(**char**\[] ch, **int** start, **int** length)

         **throws** SAXException {

      String str=**new** String(ch,start,length);

      **if**(!str.trim().equals("")){

         System.*out*.println("name:" + str);

      }

   }

   //元素结束了

   **public** **void** endElement(String uri, String localName, String name)

         **throws** SAXException {  }

然后在test方法中

**public** **static** **void** main(String\[] args)**throws** Exception {

        SAXParserFactory fac=SAXParserFactory.*newInstance*();

        SAXParser par=fac.newSAXParser();

        par.parse("f:/teas.xml", **new** SaxTest());

    }

New SaxTest是一个new出一个类的实类