백엔드 개발 XML/RSS 튜토리얼 android sax는 xml 파일을 구문 분석합니다. (2)

android sax는 xml 파일을 구문 분석합니다. (2)

Feb 09, 2017 pm 02:06 PM
Android XML 파일

在上篇文章中,简单介绍了sax解析xml的一种方式,它是继承defaultHandler方式,并重写其中的几个方法来实现的。

接下来说的第二种方式是用RootElement这个类来解析的,RootElement 内置了defaultHandler的子类,

RootElement 源码如下:

public class RootElement extends Element {  
  
    final Handler handler = new Handler();  
  
    /**  
     * Constructs a new root element with the given name.  
     *  
     * @param uri the namespace  
     * @param localName the local name  
     */  
    public RootElement(String uri, String localName) {  
        super(null, uri, localName, 0);  
    }  
  
    /**  
     * Constructs a new root element with the given name. Uses an empty string  
     * as the namespace.  
     *  
     * @param localName the local name  
     */  
    public RootElement(String localName) {  
        this("", localName);  
    }  
  
    /**  
     * Gets the SAX {@code ContentHandler}. Pass this to your SAX parser.  
     */  
    public ContentHandler getContentHandler() {  
        return this.handler;  
    }  
  
    class Handler extends DefaultHandler {  
  
        Locator locator;  
        int depth = -1;  
        Element current = null;  
        StringBuilder bodyBuilder = null;  
  
        @Override  
        public void setDocumentLocator(Locator locator) {  
            this.locator = locator;  
        }  
  
        @Override  
        public void startElement(String uri, String localName, String qName,  
                Attributes attributes) throws SAXException {  
            int depth = ++this.depth;  
  
            if (depth == 0) {  
                // This is the root element.  
                startRoot(uri, localName, attributes);  
                return;  
            }  
  
            // Prohibit mixed text and elements.  
            if (bodyBuilder != null) {  
                throw new BadXmlException("Encountered mixed content"  
                        + " within text element named " + current + ".",  
                        locator);  
            }  
  
            // If we're one level below the current element.  
            if (depth == current.depth + 1) {  
                // Look for a child to push onto the stack.  
                Children children = current.children;  
                if (children != null) {  
                    Element child = children.get(uri, localName);  
                    if (child != null) {  
                        start(child, attributes);  
                    }  
                }  
            }  
        }  
  
        void startRoot(String uri, String localName, Attributes attributes)  
                throws SAXException {  
            Element root = RootElement.this;  
            if (root.uri.compareTo(uri) != 0  
                    || root.localName.compareTo(localName) != 0) {  
                throw new BadXmlException("Root element name does"  
                        + " not match. Expected: " + root + ", Got: "  
                        + Element.toString(uri, localName), locator);  
            }  
  
            start(root, attributes);  
        }  
  
        void start(Element e, Attributes attributes) {  
            // Push element onto the stack.  
            this.current = e;  
  
            if (e.startElementListener != null) {  
                e.startElementListener.start(attributes);  
            }  
  
            if (e.endTextElementListener != null) {  
                this.bodyBuilder = new StringBuilder();  
            }  
              
            e.resetRequiredChildren();  
            e.visited = true;  
        }  
  
        @Override  
        public void characters(char[] buffer, int start, int length)  
                throws SAXException {  
            if (bodyBuilder != null) {  
                bodyBuilder.append(buffer, start, length);  
            }  
        }  
  
        @Override  
        public void endElement(String uri, String localName, String qName)  
                throws SAXException {  
            Element current = this.current;  
  
            // If we've ended the current element...  
            if (depth == current.depth) {  
                current.checkRequiredChildren(locator);  
  
                // Invoke end element listener.  
                if (current.endElementListener != null) {  
                    current.endElementListener.end();  
                }  
  
                // Invoke end text element listener.  
                if (bodyBuilder != null) {  
                    String body = bodyBuilder.toString();  
                    bodyBuilder = null;  
  
                    // We can assume that this listener is present.  
                    current.endTextElementListener.end(body);  
                }  
  
                // Pop element off the stack.  
                this.current = current.parent;  
            }  
  
            depth--;  
        }  
    }  
}
로그인 후 복사

以上是RootElement类得源码,从源码可以看出,它只是将defaultHandler简单的处理一下。


具体应用可以参照我写的测试源码

/**  
     * sax解析xml的第二种方式  
     *      用XMLReader 也是sax的一种方式  
     * @return  
     */  
    private String saxParseSecond(){  
        //读取src下xml文件  
        InputStream inputStream =  
             this.getClass().getClassLoader().getResourceAsStream("saxTest.xml");  
        SAXParserFactory factory = SAXParserFactory.newInstance();  
        try {  
            SAXParser parse = factory.newSAXParser();  
            XMLReader reader = parse.getXMLReader();  
            reader.setContentHandler(getRootElement().getContentHandler());  
            reader.parse(new InputSource(inputStream));  
        } catch (ParserConfigurationException e) {  
            e.printStackTrace();  
        } catch (SAXException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return result;  
    }
로그인 후 복사
/**   
     *    
     * @return 返回设置好处理机制的rootElement   
     */    
    private RootElement getRootElement(){    
            
        /*rootElement代表着根节点,参数为根节点的tagName*/    
        RootElement rootElement = new RootElement("classes");    
        /*获取一类子节点,并为其设置相应的事件   
         * 这里需要注意,虽然我们只设置了一次group的事件,但是我们文档中根节点下的所有   
         * group却都可以触发这个事件。   
         * */    
        Element groupElement = rootElement.getChild("group");    
        // 读到元素开始位置时触发,如读到<group>时    
        groupElement.setStartElementListener(new StartElementListener() {    
            @Override    
            public void start(Attributes attributes) {    
//                Log.i("TEST", "start");    
               String groupName =  attributes.getValue("name");  
               String groupNum =  attributes.getValue("num");  
               result = result+"groupName ="+groupName+"groupNum = "+groupNum+"\n";  
            }    
        });    
        //读到元素结束位置时触发,如读到</group>时    
        groupElement.setEndElementListener(new EndElementListener() {    
            @Override    
            public void end() {    
            }    
        });    
        Element personElement = groupElement.getChild("person");  
        //读取<person>标签触发  
        personElement.setStartElementListener(new StartElementListener() {  
              
            @Override  
            public void start(Attributes attributes) {  
                 String personName =  attributes.getValue("name");  
                 String age =  attributes.getValue("age");  
                 result = result+"personName ="+personName+"age = "+age+"\n";  
            }  
        });  
        //读取</person>标签触发  
        personElement.setEndElementListener(new EndElementListener() {  
              
            @Override  
            public void end() {  
                  
            }  
        });  
          
        Element chinese = personElement.getChild("chinese");    
//        chinese.setTextElementListener(new TextElementListener() {  
//            
//          @Override  
//          public void end(String body) {  
//              // TODO Auto-generated method stub  
//                
//          }  
//            
//          @Override  
//          public void start(Attributes attributes) {  
//              // TODO Auto-generated method stub  
//                
//          }  
//      });  
        // 读到文本的末尾时触发,这里的body即为文本的内容部分    
        chinese.setEndTextElementListener(new EndTextElementListener() {    
            @Override    
            public void end(String body) {    
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");   
                Matcher m = p.matcher(body);   
                body = m.replaceAll("");   
                result = result+"chinese ="+body;  
            }    
        });    
            
        Element english = personElement.getChild("english");    
        english.setEndTextElementListener(new EndTextElementListener() {    
            @Override    
            public void end(String body) {    
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");   
                Matcher m = p.matcher(body);   
                body = m.replaceAll("");   
               result = result+"english ="+body+"\n";  
            }    
        });    
        return rootElement;    
            
    }
로그인 후 복사

android sax는 xml 파일을 구문 분석합니다. (2)

我们都知道通过SAXParser对象解析xml的方式,这里我们又从代码中看到了利用另一个对象XMLReader进行解析,那么两者到底有什么联系和区别呢?

其实SAXParser是在SAX 1.0 定义的,而XMLReader则是在2.0中才开始出现的。你可以认为XMLReader的出现是为了替代SAXParser解析的,两者本质上干的事情是一样的,只不过XMLReader的功能更加的强悍而已。

关于XMLReader的获取方式,除了通过SAXParser的getXMLReader方法获得之外,我们还可以通过以下两种方式。

XMLReader parser=XMLReaderFactory.createXMLReader(); (1)
XMLReader parser=XMLReaderFactory.createXMLReader(String className); (2)
로그인 후 복사

以上就是 android sax解析xml文件(二)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

휴대폰에서 XML을 PDF로 변환 할 때 변환 속도가 빠르나요? 휴대폰에서 XML을 PDF로 변환 할 때 변환 속도가 빠르나요? Apr 02, 2025 pm 10:09 PM

모바일 XML에서 PDF의 속도는 다음 요인에 따라 다릅니다. XML 구조의 복잡성. 모바일 하드웨어 구성 변환 방법 (라이브러리, 알고리즘) 코드 품질 최적화 방법 (효율적인 라이브러리 선택, 알고리즘 최적화, 캐시 데이터 및 다중 스레딩 사용). 전반적으로 절대적인 답변은 없으며 특정 상황에 따라 최적화해야합니다.

휴대 전화에서 XML 파일을 PDF로 변환하는 방법은 무엇입니까? 휴대 전화에서 XML 파일을 PDF로 변환하는 방법은 무엇입니까? Apr 02, 2025 pm 10:12 PM

단일 애플리케이션으로 휴대 전화에서 직접 XML에서 PDF 변환을 완료하는 것은 불가능합니다. 두 단계를 통해 달성 할 수있는 클라우드 서비스를 사용해야합니다. 1. 클라우드에서 XML을 PDF로 변환하십시오. 2. 휴대 전화에서 변환 된 PDF 파일에 액세스하거나 다운로드하십시오.

휴대 전화에서 XML을 PDF로 변환하는 방법은 무엇입니까? 휴대 전화에서 XML을 PDF로 변환하는 방법은 무엇입니까? Apr 02, 2025 pm 10:18 PM

휴대 전화에서 XML을 PDF로 직접 변환하는 것은 쉽지 않지만 클라우드 서비스를 통해 달성 할 수 있습니다. 가벼운 모바일 앱을 사용하여 XML 파일을 업로드하고 생성 된 PDF를 수신하고 클라우드 API로 변환하는 것이 좋습니다. Cloud API는 Serverless Computing Services를 사용하고 올바른 플랫폼을 선택하는 것이 중요합니다. XML 구문 분석 및 PDF 생성을 처리 할 때 복잡성, 오류 처리, 보안 및 최적화 전략을 고려해야합니다. 전체 프로세스에는 프론트 엔드 앱과 백엔드 API가 함께 작동해야하며 다양한 기술에 대한 이해가 필요합니다.

Web.xml을 열는 방법 Web.xml을 열는 방법 Apr 03, 2025 am 06:51 AM

Web.xml 파일을 열려면 다음 방법을 사용할 수 있습니다. 텍스트 편집기 (예 : 메모장 또는 문자 메시지)를 사용하여 통합 개발 환경 (예 : Eclipse 또는 NetBeans)을 사용하여 명령을 편집하십시오 (Windows : Notepad Web.xml; Mac/Linux : Open -A Texted web.xml).

권장 XML 서식 도구 권장 XML 서식 도구 Apr 02, 2025 pm 09:03 PM

XML 서식 도구는 규칙에 따라 코드를 입력하여 가독성과 이해를 향상시킬 수 있습니다. 도구를 선택할 때는 사용자 정의 기능, 특수 상황 처리, 성능 및 사용 편의성에주의하십시오. 일반적으로 사용되는 도구 유형에는 온라인 도구, IDE 플러그인 및 명령 줄 도구가 포함됩니다.

XML을 PDF로 변환 할 수있는 모바일 앱이 있습니까? XML을 PDF로 변환 할 수있는 모바일 앱이 있습니까? Apr 02, 2025 pm 08:54 PM

XML을 PDF로 직접 변환하는 응용 프로그램은 근본적으로 다른 두 형식이므로 찾을 수 없습니다. XML은 데이터를 저장하는 데 사용되는 반면 PDF는 문서를 표시하는 데 사용됩니다. 변환을 완료하려면 Python 및 ReportLab과 같은 프로그래밍 언어 및 라이브러리를 사용하여 XML 데이터를 구문 분석하고 PDF 문서를 생성 할 수 있습니다.

XML 형식을 여는 방법 XML 형식을 여는 방법 Apr 02, 2025 pm 09:00 PM

대부분의 텍스트 편집기를 사용하여 XML 파일을여십시오. 보다 직관적 인 트리 디스플레이가 필요한 경우 Oxygen XML 편집기 또는 XMLSPy와 같은 XML 편집기를 사용할 수 있습니다. 프로그램에서 XML 데이터를 처리하는 경우 프로그래밍 언어 (예 : Python) 및 XML 라이브러 (예 : XML.etree.elementtree)를 사용하여 구문 분석해야합니다.

XML 온라인 서식 XML 온라인 서식 Apr 02, 2025 pm 10:06 PM

XML 온라인 형식 도구는 지저분한 XML 코드를 읽기 쉬운 형식으로 자동 구성하고 형식을 유지 관리합니다. XML의 구문 트리를 구문 분석하고 서식 규칙을 적용함으로써 이러한 도구는 코드의 구조를 최적화하여 유지 관리 가능성과 팀워크 효율성을 향상시킵니다.

See all articles