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

在上篇文章中,简单介绍了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中文网(www.php.cn)!


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

RSS는 자주 업데이트되는 컨텐츠를 게시하는 데 사용되는 XML 기반 형식입니다. 1. RSSFEED는 제목, 링크, 설명 등을 포함하여 XML 구조를 통해 정보를 구성합니다. 2. RSSFEED를 만들려면 XML 구조로 작성하고 언어 및 출시 날짜와 같은 메타 데이터를 추가해야합니다. 3. 고급 사용에는 멀티미디어 파일과 분류 된 정보가 포함될 수 있습니다. 4. 디버깅 중 XML 검증 도구를 사용하여 필요한 요소가 존재하고 올바르게 인코딩되도록하십시오. 5. RSSFEED 최적화는 구조를 단순하게 유지하고 페이징, 캐싱 및 유지함으로써 달성 할 수 있습니다. 이 지식을 이해하고 적용함으로써 컨텐츠를 효과적으로 관리하고 배포 할 수 있습니다.

XML의 RSS : 태그, 속성 및 구조 디코딩XML의 RSS : 태그, 속성 및 구조 디코딩Apr 24, 2025 am 12:09 AM

RSS는 컨텐츠를 게시하고 구독하는 데 사용되는 XML 기반 형식입니다. RSS 파일의 XML 구조에는 컨텐츠 항목을 나타내는 루트 요소, 요소 및 여러 요소가 포함됩니다. XML Parser를 통해 RSS 파일을 읽고 구문 분석하고 사용자는 최신 컨텐츠를 구독하고 얻을 수 있습니다.

RSS에서 XML의 장점 : 기술 깊은 다이빙RSS에서 XML의 장점 : 기술 깊은 다이빙Apr 23, 2025 am 12:02 AM

XML은 RSS에서 구조화 된 데이터, 확장 성, 크로스 플랫폼 호환성 및 구문 분석 검증의 장점을 가지고 있습니다. 1) 구조화 된 데이터는 컨텐츠의 일관성과 신뢰성을 보장합니다. 2) 확장 성은 콘텐츠 요구에 맞게 맞춤형 태그를 추가 할 수 있습니다. 3) 크로스 플랫폼 호환성은 다른 장치에서 원활하게 작동합니다. 4) 분석 및 검증 도구는 피드의 품질과 무결성을 보장합니다.

XML의 RSS : 컨텐츠 신디케이션의 핵심을 공개합니다XML의 RSS : 컨텐츠 신디케이션의 핵심을 공개합니다Apr 22, 2025 am 12:08 AM

XML에서 RSS 구현은 구조화 된 XML 형식을 통해 컨텐츠를 구성하는 것입니다. 1) RSS는 채널 정보 및 프로젝트 목록과 같은 요소를 포함하여 XML을 데이터 교환 형식으로 사용합니다. 2) RSS 파일을 생성 할 때는 사양에 따라 컨텐츠를 구성하고 구독을 위해 서버에 게시해야합니다. 3) RSS 파일은 리더 또는 플러그인을 통해 구독하여 컨텐츠를 자동으로 업데이트 할 수 있습니다.

기본 사항을 넘어서 : 고급 RSS 문서 기능기본 사항을 넘어서 : 고급 RSS 문서 기능Apr 21, 2025 am 12:03 AM

RSS의 고급 기능에는 컨텐츠 네임 스페이스, 확장 모듈 및 조건부 구독이 포함됩니다. 1) 컨텐츠 네임 스페이스는 RSS 기능을 확장합니다. 2) 메타 데이터를 추가하기 위해 Dublincore 또는 iTunes와 같은 확장 된 모듈, 3) 특정 조건에 따라 조건부 구독 필터 항목. 이러한 기능은 XML 요소 및 속성을 추가하여 정보 수집 효율성을 향상시켜 구현됩니다.

XML 백본 : RSS 피드가 구조화되는 방법XML 백본 : RSS 피드가 구조화되는 방법Apr 20, 2025 am 12:02 AM

rssfeedsusexmltostructurecontentupdates.1) xmlprovideahierarchicalstructurefordata.2) the ElementDefinesThefeed 'sidentityandContainsElements.3) elementsreent indindividualcontentpieces.4) rssisextensible, 허용 Bestpracticesin

RSS & XML : 웹 컨텐츠의 동적 듀오 이해RSS & XML : 웹 컨텐츠의 동적 듀오 이해Apr 19, 2025 am 12:03 AM

RSS 및 XML은 웹 컨텐츠 관리를위한 도구입니다. RSS는 컨텐츠를 게시하고 구독하는 데 사용되며 XML은 데이터를 저장하고 전송하는 데 사용됩니다. 컨텐츠 게시, 구독 및 업데이트 푸시와 함께 작동합니다. 사용의 예로는 RSS 게시 블로그 게시물 및 XML 저장 도서 정보가 있습니다.

RSS 문서 : 웹 신디케이션의 기초RSS 문서 : 웹 신디케이션의 기초Apr 18, 2025 am 12:04 AM

RSS 문서는 자주 업데이트되는 콘텐츠를 게시하고 구독하는 데 사용되는 XML 기반 구조 파일입니다. 주요 기능에는 1) 자동화 된 컨텐츠 업데이트, 2) 컨텐츠 집계 및 3) 브라우징 효율 향상이 포함됩니다. RSSFEED를 통해 사용자는 적시에 다른 소스에서 최신 정보를 구독하고 얻을 수 있습니다.

See all articles

핫 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 옷 제거제

Video Face Swap

Video Face Swap

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

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

메모장++7.3.1

메모장++7.3.1

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

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기