基于DOM XML学习笔记

关于XML我就不多介绍了。这里只是介绍下小弟学习DOM解析XML的代码笔记。
首先贴出XML的代码
<?xml version="1.0" encoding="UTF-8"?>
<employees>
	<employee>
		<name>tom</name>
		<sex>boy</sex>
		<age>24</age>
	</employee>
	<employee>
		<name>sara</name>
		<sex>girl</sex>
		<age>24</age>
	</employee>
</employees>


	public static void main(String[] args) {
	//建立解析工厂
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

			DocumentBuilder db = dbf.newDocumentBuilder();
			String url="D:\\workSpace\\J2SE\\src\\com\\xmlTest\\test.xml";
			// 拿到XML
			Document doc = db.parse(url);
			//去掉空白占位符
			doc.normalize();
			
//		NodeList employees = doc.getElementsByTagName("employee");
			NodeList employees = doc.getChildNodes(); 
			for(int i= 0;i<employees.getLength();i++){
				/**
				 * 简单XML格式DOM解析
				 */
				Node employee = employees.item(i);
				System.out.println(employee.getNodeName() 
						+ ":" + employee.getTextContent());	
				
			}
			}
		} catch (DOMException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


XML第二种
<?xml version="1.0" encoding="UTF-8"?>
<books>  
    <book id="12" type="chm">  
        <name>java</name>  
        <price>80</price>  
    </book>  
    <book id="15" type="pdf">  
        <name>Spring</name>  
        <price>30</price>  
    </book>  
</books> 


解析上面XML的JAVA代码部分
public void testXml2()throws Exception{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		String url="D:\\workSpace\\J2SE\\src\\com\\xmlTest\\test2.xml";
		Document doc = db.parse(url);
		doc.normalize();
		Element element = doc.getDocumentElement();  
		NodeList books = element.getElementsByTagName("book");
		Map map = new HashMap();
		for(int i=0;i<books.getLength();i++){
			Element bookElement = (Element) books.item(i);
			map.put("id", bookElement.getAttribute("id"));
			map.put("type", bookElement.getAttribute("type"));
			NodeList childNodes = bookElement.getChildNodes();
		
			for(int j=0;j<childNodes.getLength();j++){
				Node book = childNodes.item(j);
				if(book.getNodeType()==Node.ELEMENT_NODE){
					if("name".equals(book.getNodeName()))
						map.put("name", book.getFirstChild().getNodeValue());	
						
					else if("price".equals(book.getNodeName()))
					
						map.put("price", book.getFirstChild().getNodeValue());
					
					
				}
				
			}
			System.out.println(map);
		}
		
		
	}

以上是今天的学习代码总结,大家可以相互学习参考

你可能感兴趣的:(java,spring,xml,J2SE,J#)