XML文件的读取

<?xml version="1.0" encoding="gbk"?>			<!--设置编码格式为gbk-->
<!DOCTYPE hostList[
	<!ELEMENT hostList (host+)>					<!--设置文件的根节点hostList,以及子节点host,+代表可以有多个-->
	<!ELEMENT host (id ,title,types,street,floot,price)>		<!--设置host节点下的子节点 -->
]>
<hostList><!-- 必须以我们设置的规则来写xml文件不然会立即出错 -->
	<host>
		<id>1</id>
		<title>洛阳出租</title>
		<types>两室两厅</types>
		<street>洛阳龙鳞路</street>
		<floot>120</floot>
		<price>2000</price>
	</host>
	<host>
		<id>2</id>
		<title>郑州出租</title>
		<types>两室一厅</types>
		<street>金水区</street>
		<floot>100</floot>
		<price>3000</price>
	</host>
</hostList>

  解析xml文件

 

package test;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class Text {
	public static void main(String[] args) {
		
		try {
			DocumentBuilderFactory builderfactory=DocumentBuilderFactory.newInstance();//创建解析器的工厂
			DocumentBuilder builder= builderfactory.newDocumentBuilder();//创建解析器对象
			try {
				Document document=builder.parse("WebRoot/HostList.xml");//获取到xml文件,并解析xml文件
				NodeList nodelist=document.getElementsByTagName("host");//获取到所有的子节点“host”
				for (int i = 0; i < nodelist.getLength(); i++) {
					
					Node hoselist =nodelist.item(i);//获取单个host节点
					NodeList childList=hoselist.getChildNodes();//获取host节点下的所有节点
					for (int j = 0; j < childList.getLength(); j++) {//循环读取所有的节点
						Node subNode=childList.item(j);//获取host节点下的某个节点
						if(subNode.getNodeType()==Node.ELEMENT_NODE)//判断元素是否为节点元素
						{
							String name=subNode.getNodeName();//获取节点名字
							String valu=subNode.getFirstChild().getNodeValue();//获取节点下的value值
							System.out.println(name+":"+valu);//输出
						}
					}
				}
				System.out.println();
			} catch (SAXException e) {
				
				e.printStackTrace();
			} catch (IOException e) {
	
				e.printStackTrace();
			}
		} catch (ParserConfigurationException e) {
			
			e.printStackTrace();
		}
	}
}

  

posted @ 2017-02-18 14:45  小李少  阅读(147)  评论(0编辑  收藏  举报