java解析、读取xml文件,org.w3c.dom.Document

2 篇文章 0 订阅

Java DOM 的 API:
1.解析器工厂类:DocumentBuilderFactory

创建的方法:DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

2.解析器:DocumentBuilder

创建方法:通过解析器工厂类来获得 DocumentBuilder db = dbf.newDocumentBuilder();

3.文档树模型Document

创建方法:a.通过xml文档 Document doc = db.parse("bean.xml");  

     b.将需要解析的xml文档转化为输入流 InputStream is = new FileInputStream("bean.xml"); Document doc = db.parse(is); 

Document对象代表了一个XML文档的模型树,所有的其他Node都以一定的顺序包含在Document对象之内,排列成一个树状结构,以后对XML文档的所有操作都与解析器无关,

直接在这个Document对象上进行操作即可;

package util;

import java.io.File;
import java.io.FileInputStream;
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.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlUtil {
	
	public static void main(String[] args){
		try {
			//得到DOM解析器的工厂实例
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			//从DOM工厂中获得DOM解析器
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			/*String xmlFile = "web-context.xml";
			File file = new File(xmlFile);
			Document doc = db.parse(file);*/
			
			/*String xmlFile = "web-contextt.xml";
			FileInputStream is = new FileInputStream(xmlFile);
			Document doc = db.parse(is);*/
			
			//把要解析的xml文档读入DOM解析器
			String xmlFile = "web-context.xml";
			Document doc = db.parse(xmlFile);
			
			Element root = doc.getDocumentElement();
			System.out.println(root.getTagName());

			NodeList nodes =  doc.getElementsByTagName("bean");
			
			int length = nodes.getLength();
			for(int i=0;i<length;i++){
				Element el = (Element)nodes.item(i);
				String name = el.getAttribute("name");
				name = name.replace("/", "");
				System.out.println(name);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

<?xml version="1.0" encoding="GB2312" ?>
<beans>
	<description>定义web层的资源</description>
   	<bean name="/unitPrice.do">
    	<property name="commandName">
      		<value>form</value>
  		</property>
  	</bean>
  
   	<bean name="/assetCounterAsset.do">
	    <property name="commandName">
	      <value>form</value>
	  	</property>
  	</bean>

  	<bean name="/projectByNode.do">
		<description>下拉选择框的公共Controller</description>
		<property name="viewName">
			<value>pubView</value>
		</property>
  	</bean>

 	<bean name="/assetParamValue.do">
    	<property name="commandName">
      		<value>form</value>
  		</property>
  	</bean>
</beans>






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值