>  기사  >  백엔드 개발  >  java에서 xml을 구문 분석하기 위해 sax를 사용하는 솔루션

java에서 xml을 구문 분석하기 위해 sax를 사용하는 솔루션

高洛峰
高洛峰원래의
2017-01-11 12:56:121982검색

Java에서는 xml 문서를 기본적으로 구문 분석하는 두 가지 방법이 있습니다. 즉, Dom 구문 분석과 Sax 구문 분석

Dom 구문 분석은 강력하며 추가, 삭제, 수정 및 확인할 수 있습니다. 작업 중 문서 객체로 메모리에 읽어들이는 방식이므로 작은 문서에 적합합니다

Sax 파싱은 내용을 처음부터 끝까지 한 줄씩 읽어서 수정하는 것이 더 불편합니다. 대용량 읽기 전용 문서에 적합

이 문서에서는 Sax 구문 분석을 주로 설명하고 나머지는 생략합니다

Sax는 이벤트 기반 접근 방식을 사용하여 문서를 구문 분석합니다. 쉽게 말하면 영화관에서 영화를 보는 것과 같다. 뒤로 돌아가지 않고 처음부터 끝까지 볼 수 있다. (돔은 앞뒤로 읽을 수 있다.)

영화를 보는 과정에서 매회 줄거리, 눈물, 어깨 마찰을 만나면 뇌와 신경을 동원하여 이 정보를 수신하거나 처리합니다

마찬가지로 Sax의 구문 분석 과정에서 문서의 시작과 끝을 읽고, 요소의 시작과 끝은 일부 콜백 메서드를 트리거하므로 이러한 콜백 메서드에서 해당 이벤트 처리를 수행할 수 있습니다

네 가지 메서드는 startDocument(), endDocument(), startElement(), endElement

게다가, 가볍게 읽는 것만으로는 노드에 가는 것만으로는 충분하지 않습니다. 요소에 포함된 내용을 신중하게 처리하기 위한 문자() 메소드도 필요합니다.

이러한 콜백 메소드를 모아서 클래스

일반적으로 문서를 Main 메소드에서 읽어오는데, 이것이 바로 이벤트 기반 파싱 방식입니다

.

java에서 xml을 구문 분석하기 위해 sax를 사용하는 솔루션

위와 같이 트리거에서는 먼저 문서 읽기를 시작한 다음 요소를 하나씩 구문 분석하기 시작합니다.

메소드를 사용하고 요소 읽기를 종료합니다. 모든 요소를 ​​읽은 후 문서를 종료합니다.

이제 트리거 클래스를 생성하기 시작합니다. SaxHandler를 생성하고 해당 메서드를 재정의하는 DefaultHandler

:

import org.xml.sax.Attributes; 
import org.xml.sax.SAXException; 
import org.xml.sax.helpers.DefaultHandler; 

  
public class SaxHandler extends DefaultHandler { 

    /* 此方法有三个参数 
       arg0是传回来的字符数组,其包含元素内容 
       arg1和arg2分别是数组的开始位置和结束位置 */ 
    @Override 
    public void characters(char[] arg0, int arg1, int arg2) throws SAXException { 
        String content = new String(arg0, arg1, arg2); 
        System.out.println(content); 
        super.characters(arg0, arg1, arg2); 
    } 

    @Override 
    public void endDocument() throws SAXException { 
        System.out.println("\n…………结束解析文档…………"); 
        super.endDocument(); 
    } 

    /* arg0是名称空间 
       arg1是包含名称空间的标签,如果没有名称空间,则为空 
       arg2是不包含名称空间的标签 */ 
    @Override 
    public void endElement(String arg0, String arg1, String arg2) 
            throws SAXException { 
        System.out.println("结束解析元素  " + arg2); 
        super.endElement(arg0, arg1, arg2); 
    } 

    @Override 
    public void startDocument() throws SAXException { 
        System.out.println("…………开始解析文档…………\n"); 
        super.startDocument(); 
    } 

    /*arg0是名称空间 
      arg1是包含名称空间的标签,如果没有名称空间,则为空 
      arg2是不包含名称空间的标签 
      arg3很明显是属性的集合 */
    @Override
    public void startElement(String arg0, String arg1, String arg2, 
            Attributes arg3) throws SAXException { 
        System.out.println("开始解析元素 " + arg2); 
        if (arg3 != null) { 
            for (int i = 0; i < arg3.getLength(); i++) { 
                 // getQName()是获取属性名称, 
                System.out.print(arg3.getQName(i) + "=\"" + arg3.getValue(i) + "\""); 
            } 
        } 
        System.out.print(arg2 + ":"); 
        super.startElement(arg0, arg1, arg2, arg3); 
    } 
}

XML 문서:

<?xml version="1.0" encoding="UTF-8"?>  
<books>  
   <book id="001">  
      <title>Harry Potter</title>  
      <author>J K. Rowling</author>  
   </book>  
   <book id="002">  
      <title>Learning XML</title>  
      <author>Erik T. Ray</author>  
   </book>  
</books>

TestDemo 테스트 클래스:

import java.io.File; 

import javax.xml.parsers.SAXParser; 
import javax.xml.parsers.SAXParserFactory; 

  
public class TestDemo { 

    public static void main(String[] args) throws Exception { 
        // 1.实例化SAXParserFactory对象 
        SAXParserFactory factory = SAXParserFactory.newInstance(); 
        // 2.创建解析器 
        SAXParser parser = factory.newSAXParser(); 
        // 3.获取需要解析的文档,生成解析器,最后解析文档 
        File f = new File("books.xml"); 
        SaxHandler dh = new SaxHandler(); 
        parser.parse(f, dh); 
    } 
}

출력 결과:

…………开始解析文档………… 

开始解析元素 books 
books:  

开始解析元素 book 
id="001"book:  

开始解析元素 title 
title:Harry Potter 
结束解析元素  title 

        
开始解析元素 author 
author:J K. Rowling 
结束解析元素  author 

     
结束解析元素  book 

     
开始解析元素 book 
id="002"book:  

开始解析元素 title 
title:Learning XML 
结束解析元素  title 

        
开始解析元素 author 
author:Erik T. Ray 
结束解析元素  author 

     
结束解析元素  book 

  
结束解析元素  books 

…………结束解析文档…………

위에서는 실행 프로세스를 올바르게 표시했지만 출력은 매우 지저분합니다.

이 프로세스를 보다 명확하게 실행하기 위해 SaxHandler를 다시 작성하여 원본을 복원할 수도 있습니다. xml 문서

다시 작성된 SaxHandler 클래스:

import org.xml.sax.Attributes; 
import org.xml.sax.SAXException; 
import org.xml.sax.helpers.DefaultHandler; 

  
public class SaxHandler extends DefaultHandler { 

    @Override
    public void characters(char[] arg0, int arg1, int arg2) throws SAXException { 
        System.out.print(new String(arg0, arg1, arg2)); 
        super.characters(arg0, arg1, arg2); 
    } 

    @Override
    public void endDocument() throws SAXException { 
        System.out.println("\n结束解析"); 
        super.endDocument(); 
    } 

    @Override
    public void endElement(String arg0, String arg1, String arg2) 
            throws SAXException { 
        System.out.print("</"); 
        System.out.print(arg2); 
        System.out.print(">"); 
        super.endElement(arg0, arg1, arg2); 
    } 

    @Override
    public void startDocument() throws SAXException { 
        System.out.println("开始解析"); 
        String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; 
        System.out.println(s); 
        super.startDocument(); 
    } 

    @Override
    public void startElement(String arg0, String arg1, String arg2, 
            Attributes arg3) throws SAXException { 

        System.out.print("<"); 
        System.out.print(arg2); 

        if (arg3 != null) { 
            for (int i = 0; i < arg3.getLength(); i++) { 
                System.out.print(" " + arg3.getQName(i) + "=\"" + arg3.getValue(i) + "\""); 
            } 
        } 
        System.out.print(">"); 
        super.startElement(arg0, arg1, arg2, arg3); 
    } 

}

sax를 사용하여 Java에서 xml을 구문 분석하는 솔루션과 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트에 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.