android解析XML

直接上代码:


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
	
	private static final String TAG = "xxxxxxxxx";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager lm = (LocationManager)getSystemService(LOCATION_SERVICE);
        Log.i("xxxxxxxyyyyyyyyy", lm.toString());
        // 解析XML
		parseXML1();  // XmlPullParser
		
		parseXML2();  // XmlPullParser
		
		parseXML3();  // DOM
		
		parseXML4(); // SAX
    }
    
    // 适合没有子标签的XML
    private void parseXML1 () {
    	try {
    		
    		// XML字符串
    		StringBuilder sb = new StringBuilder();
    		sb.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>")
    			.append("<users><user name=\"allei\"></user><user name=\"boss\"></user></users>");
			
    		// 相关准备
    		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser parser = factory.newPullParser();
			parser.setInput(new StringReader(sb.toString()));
			
			// 开始解析
			int type = parser.getEventType();
			
			while (type != XmlPullParser.END_DOCUMENT) {
				switch (type) {
					case XmlPullParser.START_DOCUMENT :
						Log.i(TAG, "START_DOCUMENT");
						break;
					case XmlPullParser.END_DOCUMENT :
						Log.i(TAG, "END_DOCUMENT");
						break;
					case XmlPullParser.END_TAG : 
						Log.i(TAG, "END_TAG");
						break;
					case XmlPullParser.START_TAG :
						String tagName = parser.getName();
						if (tagName.equals("user")) {
							String value = parser.getAttributeValue(null, "name");
							Log.i("xxxxxxxxxparseXML1()", "name = " + tagName + "; value = " + value);
						}
				}
				type = parser.next();
			}
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    // 适合没有子标签的XML
    private void parseXML2 () {
    	XmlPullParser parser = getResources().getXml(R.xml.test);
		try {
			while (parser.next() != XmlPullParser.END_DOCUMENT) {

				String name = parser.getName();
				if ((name != null)
						&& (name.equals("Book") || name
								.equals("User"))) {

					for (int i = 0; i < parser.getAttributeCount(); i++) {
						String attribute = parser.getAttributeName(i);
						if ((attribute != null) && attribute.equals("name")) {
							String component_name = parser.getAttributeValue(i);
							Log.i("xxxxxparseXML2()", component_name);
						}
					}

				} // end if...

			} // end while...

		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    // 适合体积小且含有子标签的XML
    private void parseXML3 () {
    	try {
    		StringBuilder sb = new StringBuilder();
			sb.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>")
				.append("<users>")
				.append("<user id=\"100\"><name>allei</name><age>20</age></user>")
				.append("<user id=\"200\"><name>boss</name><age>40</age></user>")
				.append("</users>");
	    	ByteArrayInputStream bais = new ByteArrayInputStream(sb.toString().getBytes());
			
	    	
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder  builder = factory.newDocumentBuilder();
			Document document = builder.parse(bais);		
			
			Element root = document.getDocumentElement();	
			NodeList nodes = root.getElementsByTagName("user");
			
			String id = "";
			String name = "";
			String age = "";
			for(int i=0; i < nodes.getLength(); i++){
				Element personElement = (Element)nodes.item(i);//element /text == node
				id = personElement.getAttribute("id");
				
				NodeList childnodes = personElement.getChildNodes();			
				for(int j=0; j<childnodes.getLength(); j++ ){				
					Node childNode = (Node)childnodes.item(j);
					
					if(childNode.getNodeType() == Node.ELEMENT_NODE){
						Element childElement = (Element)childNode;
						if("name".equals(childElement.getNodeName())){
							name = childElement.getFirstChild().getNodeValue();
						} else if("age".equals(childElement.getNodeName())){
							age = childElement.getFirstChild().getNodeValue();
							Log.i("xxxxxxxxparseXML3()", "id=" + id + "; name=" + name + "; age=" + age);
						}
					}
				}
			}
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    // 适合体积大,且有子标签的元素。可读性不好。
    private void parseXML4 () {
    	try {
    		StringBuilder sb = new StringBuilder();
			sb.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>")
				.append("<users>")
				.append("<user id=\"100\"><name>allei</name><age>20</age></user>")
				.append("<user id=\"200\"><name>boss</name><age>40</age></user>")
				.append("</users>");
	    	ByteArrayInputStream bais = new ByteArrayInputStream(sb.toString().getBytes());
    		
    		SAXParserFactory spf = SAXParserFactory.newInstance();
    		SAXParser parser = spf.newSAXParser();
    		MyXMLContentHandler handler = new MyXMLContentHandler(); // 要定义一个handler
    		parser.parse(bais, handler);
    		bais.close();
    		
    		String result = handler.getResult();
    		Log.i("xxxxxxxxxxxxparseXML4()", result);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    private class MyXMLContentHandler extends DefaultHandler {
    	private String preTag; // 上一个标签
    	private StringBuilder sb = new StringBuilder();
    	
    	
    	public String getResult () {
    		return sb.toString();
    	}
    	
    	// 接收文档的开始的通知
    	@Override
    	public void startDocument() throws SAXException {
    	}
    	
    	// 接收字符数据的通知
    	@Override
    	public void characters(char[] ch, int start, int length) throws SAXException {
    		String data = new String(ch, start, length);
    		if ("name".equals(preTag)) {
    			sb.append("; name=" + data);
    		} else if ("age".equals(preTag)) {
    			sb.append("; age=" + data + "]");
    		}
    	}
    	
    	// 接收元素开始的通知
    	@Override
    	public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    		if ("user".equals(localName)) {
    			sb.append("[id=" + attrs.getValue("", "id"));
    		}
    		
    		preTag = localName;
    	}
    	
    	@Override
    	public void endElement(String uri, String localName, String qName) {
    		preTag = null;
    	}
    }


test.xml

<?xml version="1.0" encoding="utf-8"?>
<Preference xmlns:android="http://schemas.android.com/apk/res/android">
   	<Books>
 		<Book name="Thinking in Fuck"/>
 		<Book name="Thinking in Java"/>
 	</Books>

 	<Users>
  		<User name="Alex"/>
  		<User name="Alex II"/>
 	</Users>
</Preference>



你可能感兴趣的:(exception,android,String,user,encoding,attributes)