Java解析XMl文件之SAX和DOm方法

时间:2022-10-30 13:18:04

如题,这两种方法的jar包都在jdk中,不需要下载。

先来说下目录结构:

Java解析XMl文件之SAX和DOm方法

首先建一个Peron类封装person.xml的属性;DomParseService和SaxParseService分别为两种解析方法的服务类。最后TestXml为测试类。

Person.xml如下:

 <?xml version="1.0" encoding="gbk"?>
 <Persons>
     <Person id="1">
         <name>zhangsan</name>
         <sex>男</sex>
         <age>30</age>
     </Person>
     <Person id="2">
         <name>lisi</name>
         <sex>女</sex>
         <age>20</age>
     </Person>
 </Persons>

Java解析XMl文件之SAX和DOm方法

  • SAX方法:
 public class SaxParseService extends DefaultHandler {
     private List<Person> mPersons = null;
     private Person mPerson = null;
     private String m_preTag = null;

     public List<Person> getPersons(InputStream xmlStream)
             throws ParserConfigurationException, SAXException, IOException {
         SAXParserFactory factory = SAXParserFactory.newInstance();
         SAXParser parser = factory.newSAXParser();
         SaxParseService handler = new SaxParseService();
         parser.parse(xmlStream, handler);
         return handler.getPersons();
     }

     private List<Person> getPersons() {
         return mPersons;
     }

     @Override
     public void startDocument() throws SAXException {
         mPersons = new ArrayList<Person>();
     }

     @Override
     public void startElement(String uri, String localName, String qName,
             Attributes attributes) throws SAXException {
         if ("Person".equals(qName)) {
             mPerson = new Person();
             mPerson.setId(Integer.parseInt(attributes.getValue(0)));
         }
         m_preTag = qName;
     }

     @Override
     public void endElement(String uri, String localName, String qName)
             throws SAXException {
         if ("Person".equals(qName)) {
             mPersons.add(mPerson);
             mPerson = null;
         }
         m_preTag = null;
     }

     @Override
     public void characters(char[] ch, int start, int length)
             throws SAXException {
         if (m_preTag != null) {
             String content = new String(ch, start, length);
             if ("name".equals(m_preTag)) {
                 mPerson.setName(content);
             } else if ("sex".equals(m_preTag)) {
                 mPerson.setSex(content);
             } else if ("age".equals(m_preTag)) {
                 mPerson.setAge(Integer.parseInt(content));
             }
         }
     }

 }
  • DOM方法:
 public class DomParseService {
     public List<Person> getPersons(InputStream is)
             throws ParserConfigurationException, SAXException, IOException {
         List<Person> mPersons = new ArrayList<Person>();
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder builder = factory.newDocumentBuilder();
         Document element = builder.parse(is);
         NodeList PersonNodes = element.getElementsByTagName("Person");
         for (int i = 0; i < PersonNodes.getLength(); i++) {
             Element PersonElement = (Element) PersonNodes.item(i);
             Person mPerson = new Person();
             mPerson.setId(Integer.parseInt(PersonElement.getAttribute("id")));
             NodeList ChildNodes = PersonElement.getChildNodes();
             for (int j = 0; j < ChildNodes.getLength(); j++) {
                 if (ChildNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
                     if("name".equals(ChildNodes.item(j).getNodeName())){
                         mPerson.setName(ChildNodes.item(j).getFirstChild().getNodeValue());
                     }else if("sex".equals(ChildNodes.item(j).getNodeName())){
                         mPerson.setSex(ChildNodes.item(j).getFirstChild().getNodeValue());
                     }else if("age".equals(ChildNodes.item(j).getNodeName())){
                         mPerson.setAge(Integer.parseInt(ChildNodes.item(j).getFirstChild().getNodeValue()));
                     }
                 }
             }
             mPersons.add(mPerson);
         }
         return mPersons;

     }
 }

测试类如下。里面正对SAX和DOM分别写了两个方法:

 public class TestXml {

     public static void main(String[] args) {
         SaxParse();
         DomParse();
     }
     public static void DomParse() {
         DomParseService dps=new DomParseService();
         try {
             List<Person> mPersons=dps.getPersons(new FileInputStream(new File("e:/Person.xml")));
             for(Person p:mPersons){
                 System.out.println(p.getName());
             }
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (ParserConfigurationException e) {
             e.printStackTrace();
         } catch (SAXException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
     public static void SaxParse() {
         SaxParseService sps=new SaxParseService();
         try {
              List<Person> Persons=sps.getPersons(new FileInputStream(new File("e:/Person.xml")));
             for(Person p:Persons){
                 System.out.println(p.getName());
             }
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (ParserConfigurationException e) {
             e.printStackTrace();
         } catch (SAXException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }

 }