Menu Home

Android使用SAX解析XML

               String xml = "<?xml version=\"1.0\"?>\n" 
	                    + "<user>\n"
	                    + "<name>lnmcc</name>\n" 
	                    + "<age>10</age>\n";
	class XMLUser {

		String name;
		String age;

		public XMLUser() {
			name = "";
			age = "";
		}
	}
	private class UserXMLHandler extends DefaultHandler {

		static final int NONE = 0;
		static final int NAME = 1;
		static final int AGE = 2;

		int state = NONE;

		static final String NAME_ELEMENT = "name";
		static final String AGE_ELEMENT = "age";

		@Override
		public void startDocument() throws SAXException {
			aUser = new XMLUser();
		}

		@Override
		public void endDocument() throws SAXException {

		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			
			if(localName.equalsIgnoreCase(NAME_ELEMENT)) {
				state = NAME;
			} else if(localName.equalsIgnoreCase(AGE_ELEMENT)) {
				state = AGE;
			} else {
				state = NONE;
			}
		}
		
		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			
		}
		
		@Override
		public void characters(char[] ch, int start, int length)   throws SAXException {
			
			String stringChars = new String(ch, start, length);
			if(state == NAME) {
				aUser.name += stringChars.trim();
			} else if(state == AGE) {
				aUser.age += stringChars.trim();
		}
	}
		SAXParserFactory aSaxParserFactory = SAXParserFactory.newInstance();

		try {
			SAXParser aSaxParser = aSaxParserFactory.newSAXParser();
			XMLReader anXMLReader = aSaxParser.getXMLReader();
			UserXMLHandler aUserXMLHandler = new UserXMLHandler();
			anXMLReader.setContentHandler(aUserXMLHandler);

			anXMLReader.parse(new InputSource(new ByteArrayInputStream(xml.getBytes())));
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

Android使用Pull解析XML在 这里

Categories: android应用 java

Tagged as:

lnmcc

1 reply

Leave a Reply

Your email address will not be published.