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

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

Feb 17, 2017 pm 03:09 PM

在上篇文章中,简单介绍了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;  
          
    }



我们都知道通过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中文网(m.sbmmt.com)!


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

핫 AI 도구

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

뜨거운 주제

PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? Feb 07, 2025 am 11:57 AM

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

Xiaomi Redmi Note 14 Pro Plus는 Light Hunter 800 카메라를 탑재한 최초의 Qualcomm Snapdragon 7s Gen 3 스마트폰으로 출시됩니다. Xiaomi Redmi Note 14 Pro Plus는 Light Hunter 800 카메라를 탑재한 최초의 Qualcomm Snapdragon 7s Gen 3 스마트폰으로 출시됩니다. Sep 27, 2024 am 06:23 AM

Redmi Note 14 Pro Plus는 이제 작년 Redmi Note 13 Pro Plus(Amazon에서 현재 $375)의 직접적인 후속 제품으로 공식화되었습니다. 예상대로 Redmi Note 14 Pro Plus는 Redmi Note 14 및 Redmi Note 14 Pro와 함께 Redmi Note 14 시리즈를 주도합니다. 리

Oppo Find X8 디자인은 초기 이미지에서 Apple iPhone 16 Pro와 OnePlus Open의 교차점처럼 보입니다. Oppo Find X8 디자인은 초기 이미지에서 Apple iPhone 16 Pro와 OnePlus Open의 교차점처럼 보입니다. Sep 28, 2024 am 06:04 AM

역사적으로 Oppo는 2018년 6월에 발표한 오리지널 Find X를 제외하고 늦겨울이나 초봄에 주력 제품인 'Find X' 시리즈를 새로 고쳤습니다. 이를 위해 Find X7과 Find X7 Ultra는 출시된 지 6개월이 채 되지 않았습니다. 이 시점에서. 시간

Xiaomi Redmi Note 14, Redmi Note 14 Pro and Redmi Note 14 Pro Plus to shake up mid-range smartphone market with Gorilla Glass Victus 2 and IP69 certification Xiaomi Redmi Note 14, Redmi Note 14 Pro and Redmi Note 14 Pro Plus to shake up mid-range smartphone market with Gorilla Glass Victus 2 and IP69 certification Sep 24, 2024 pm 12:15 PM

Xiaomi has just announced the release date for its next Redmi Note smartphones. As expected, these are set to arrive as three Redmi Note 14 series handsets. More specifically, the company intends to release the Redmi Note 14, Redmi Note 14 Pro and Re

C 및 XML : 관계와 지원 탐색 C 및 XML : 관계와 지원 탐색 Apr 21, 2025 am 12:02 AM

C는 XML과 타사 라이브러리 (예 : TinyXML, Pugixml, Xerces-C)와 상호 작용합니다. 1) 라이브러리를 사용하여 XML 파일을 구문 분석하고 C- 처리 가능한 데이터 구조로 변환하십시오. 2) XML을 생성 할 때 C 데이터 구조를 XML 형식으로 변환하십시오. 3) 실제 애플리케이션에서 XML은 종종 구성 파일 및 데이터 교환에 사용되어 개발 효율성을 향상시킵니다.

삼성 갤럭시 Z 폴드 스페셜 에디션, 상충되는 이름 등장으로 10월 말 출시 예정 삼성 갤럭시 Z 폴드 스페셜 에디션, 상충되는 이름 등장으로 10월 말 출시 예정 Oct 01, 2024 am 06:21 AM

오랫동안 기다려온 삼성의 '스페셜 에디션' 폴더블 출시가 또 다른 반전을 가져왔습니다. 최근 몇 주 동안 이른바 갤럭시 Z 폴드 스페셜 에디션에 대한 소문은 다소 잠잠해졌습니다. 대신 갤럭시 S25 시리즈로 초점이 옮겨졌습니다.

Lenovo, 2024 Legion Y700 게이밍 태블릿의 새로운 색상 옵션 공개 Lenovo, 2024 Legion Y700 게이밍 태블릿의 새로운 색상 옵션 공개 Sep 29, 2024 am 06:05 AM

Lenovo는 9월 29일 중국에서 2024년형 Legion Y700 출시를 준비하고 있습니다. 이 새로운 Android 게임 태블릿은 RedMagic Nova와 경쟁하게 될 것이며 회사는 이미 장치의 거의 모든 사양을 확인했습니다. 이제 가득 차기 몇 시간 전

XML/RSS 데이터 통합 ​​: 개발자 및 건축가를위한 실용 가이드 XML/RSS 데이터 통합 ​​: 개발자 및 건축가를위한 실용 가이드 Apr 02, 2025 pm 02:12 PM

XML/RSS 파일을 구문 분석하고 생성하여 XML/RSS 데이터 통합을 달성 할 수 있습니다. 1) Python의 xml.etree.elementtree 또는 FeedParser 라이브러리를 사용하여 XML/RSS 파일을 구문 분석하고 데이터를 추출하십시오. 2) ElementTree를 사용하여 XML/RSS 파일을 생성하고 점차 노드와 데이터를 추가하십시오.

See all articles