第一种dom解析:
String xml = "<persons>" + "<person>" + "<name>amos</name>" + "<age>30</age>" + "</person>" + "<person>" + "<name>tom</name>" + "<age>18</age>" + "</person>" + "</persons>"; DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document parse = builder.parse(new ByteArrayInputStream(xml.getBytes())); Element element = parse.getDocumentElement(); NodeList nodes = element.getElementsByTagName("person"); for (int i = 0; i < nodes.getLength(); i++) { NodeList person = nodes.item(i).getChildNodes(); for (int j = 0; j < person.getLength(); j++) { if (person.item(j) instanceof Element) Log.d("TAG","name:" + person.item(j).getNodeName() + ",value:" + person.item(j).getTextContent()); } }
第二种sax解析:
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); saxParser.parse(new ByteArrayInputStream(xml.getBytes()), new MyDefaultHandler()); class MyDefaultHandler extends DefaultHandler { String currentTag; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); currentTag = localName; } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); String value = new String(ch, start, length); // 将当前TextNode转换为String Log.d("TAG","name:" + currentTag + ",value:" + value); } }
第三种pull解析:
XmlPullParser xmlPullParser = XmlPullParserFactory.newInstance().newPullParser(); xmlPullParser.setInput(new ByteArrayInputStream(xml.getBytes()), "UTF-8"); int eventType = xmlPullParser.getEventType(); boolean isEnd = false; while (!isEnd) { switch (eventType) { case XmlPullParser.START_DOCUMENT: Log.d("TAG","START_DOCUMENT---name:" + xmlPullParser.getName()); break; case XmlPullParser.START_TAG: if (xmlPullParser.getName().equals("name")) { String name = xmlPullParser.nextText(); Log.d("TAG","name:" + xmlPullParser.getName() + ",value:" + name); } else if (xmlPullParser.getName().equals("age")) { String name = xmlPullParser.nextText(); Log.d("TAG","name:" + xmlPullParser.getName() + ",value:" + name); } break; case XmlPullParser.END_TAG: Log.d("TAG","END_TAG---name:" + xmlPullParser.getName()); break; case XmlPullParser.END_DOCUMENT: Log.d("TAG","END_DOCUMENT---name:" + xmlPullParser.getName()); isEnd = true; break; } eventType = xmlPullParser.next(); }
原文地址:https://www.cnblogs.com/BruceV/p/12038476.html
时间: 2024-11-08 23:44:03