XML数据解析之DOM解析

前端之家收集整理的这篇文章主要介绍了XML数据解析之DOM解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


private void domParserXml(InputStream xmlInputStream) {	
				Log.i(TAG,"begin domParserXml");
				try {
					DocumentBuilderFactory xmlBuilderFactory=DocumentBuilderFactory.newInstance();
					DocumentBuilder xmlBuilder= xmlBuilderFactory.newDocumentBuilder();
					if(xmlInputStream==null){
						Log.e(TAG,"domParserXml xmlInputStream==null");
						return;
					}
					Document xml=xmlBuilder.parse(xmlInputStream);
					//获取根节点
					Element rootElement= xml.getDocumentElement();
					
					parserRoot(rootElement);
					
				} catch (SAXException e) {
					Log.w(TAG,"SAXException");
				} catch (IOException e) {
					Log.w(TAG,"IOException");
				}catch (ParserConfigurationException e) {
					Log.w(TAG,"ParserConfigurationException");
				}
			}
			String monthvalue=null;
			String dayvalue=null;
			private void parserRoot(Element rootElement) {
				NodeList nList=rootElement.getChildNodes();
				int len=nList.getLength();
				for (int i = 0; i < len; i++) {
					Node xmlNode=nList.item(i);
					String nameString=xmlNode.getNodeName();
					short type=xmlNode.getNodeType();
					
					if(nameString.equals("month")||nameString.equals("day")){
						monthvalue=xmlNode.getAttributes().getNamedItem("value").getNodeValue();
						//Log.i(TAG,nameString +"value="+value);	
					}
					if(nameString.equals("day")){
						dayvalue=xmlNode.getAttributes().getNamedItem("value").getNodeValue();
						//Log.i(TAG,nameString +"value="+value);	
					}
					if(nameString.equals("bill")){
						String starttime=xmlNode.getAttributes().getNamedItem("starttime").getNodeValue();
						String endtime=xmlNode.getAttributes().getNamedItem("endtime").getNodeValue();
						String name=xmlNode.getAttributes().getNamedItem("name").getNodeValue();
						String value1=xmlNode.getAttributes().getNamedItem("value").getNodeValue();
						
						ContentValues values=new ContentValues();
						//values.put("_id",1);
						values.put("month",monthvalue);
						values.put("day",dayvalue);
						values.put("start",starttime);
						values.put("end",endtime);
						values.put("name1",name);
						values.put("value",value1);
						getContentResolver().insert(Uri.parse("content://com.stamars.sqlite.sqlite/channel"),values);
						//Log.i(TAG,starttime+" "+starttime+" endtime "+endtime+" name "+name+" value "+value1);
					}						
					//Log.i(TAG,"name="+nameString+",type="+type+",value="+value+",hasattr="+xmlNode.hasAttributes());
					if(xmlNode.hasChildNodes()&&xmlNode.getNodeType()==Document.ELEMENT_NODE)
						parserRoot((Element) xmlNode);
				}
				
			}
		});
	}
原文链接:https://www.f2er.com/xml/299172.html

猜你在找的XML相关文章