java读写xml文件

有两种方法一种是利用jdk自带的(里面的javax.xml.parsers包和org.w3c.dom包),另一种是利用dom4j架包,相比下我觉的dom4j更好,更加明了;jdk自带的那种利用节点链的数据结构,我觉的他更加复杂化了问题,刚看可能摸不着头脑。废话不多说了,来读下下面的xml

<?xml version="1.0" encoding="UTF-8"?>
<setting>

	<database>
		<use_sql>Oracle</use_sql>
		<dialect>
			<MySQL>org.hibernate.dialect.MySQLDialect</MySQL>
			<Ms_SQL_Server>org.hibernate.dialect.SQLServerDialect</Ms_SQL_Server>
			<Oracle>org.hibernate.dialect.Oracle10gDialect</Oracle>
		</dialect>
		<driver>oracle.jdbc.driver.OracleDriver</driver>
 
		<url>jdbc:oracle:thin:@127.0.0.1:1521:wait</url>
		<user>system</user>
		<password>123456</password>
	</database>
	
	<program>
		<paging>20</paging>
	</program>
	
</setting>

1、先来jdk自带的那种:
(1)读文件:
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = dbf.newDocumentBuilder();
			Document xmlDoc = builder.parse("setting.xml");
			NodeList nodeList = xmlDoc.getElementsByTagName("database");
			NodeList databaseList = nodeList.item(0).getChildNodes();
			for(int i = 0, len = databaseList.getLength(); i < len; i++)
			{
				Node childNode = databaseList.item(i);
				if (childNode instanceof Element) 
				{  
					String childName = childNode.getNodeName();
					if("use_sql".equals(childName))
						useSql = childNode.getFirstChild().getNodeValue();
					else if("dialect".equals(childName))
					{
						NodeList dialectNodeList = childNode.getChildNodes();
						for(int j = 0, len2 = dialectNodeList.getLength(); j < len2; j++)
						{
							Node dialectNode = dialectNodeList.item(j);
							if(dialectNode instanceof Element)
							{
								String dialectName = dialectNode.getNodeName();
								String dialectValue = dialectNode.getFirstChild().getNodeValue();
								dialect.put(dialectName, dialectValue);
							}
						}	
						
					}
					else if("driver".equals(childName))
						driver = childNode.getFirstChild().getNodeValue();
					else if("url".equals(childName))
						url = childNode.getFirstChild().getNodeValue();
					else if("user".equals(childName))
						user = childNode.getFirstChild().getNodeValue();
					else if("password".equals(childName))
						password = childNode.getFirstChild().getNodeValue();
				}
			}
			
			nodeList = xmlDoc.getElementsByTagName("program");
			databaseList = nodeList.item(0).getChildNodes();
			for(int i = 0, len = databaseList.getLength(); i < len; i++)
			{
				Node childNode = databaseList.item(i);
				if (childNode instanceof Element) 
				{  
					String childName = childNode.getNodeName();
					if("paging".equals(childName))
					{
						paging = childNode.getFirstChild().getNodeValue();
						break;
					}
				}
			}	



(2)写文件
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = dbf.newDocumentBuilder();
			Document xmlDoc = builder.parse("setting.xml");
			NodeList nodeList = xmlDoc.getElementsByTagName("database");
			NodeList databaseList = nodeList.item(0).getChildNodes();
			for(int i = 0, len = databaseList.getLength(); i < len; i++)
			{
				Node childNode = databaseList.item(i);
				if (childNode instanceof Element) 
				{  
					String childName = childNode.getNodeName();
					if("use_sql".equals(childName))
						childNode.getFirstChild().setNodeValue(useSql);
					else if("driver".equals(childName))
						childNode.getFirstChild().setNodeValue(getDriver(useSql));
					else if("url".equals(childName))
						childNode.getFirstChild().setNodeValue(url);
					else if("user".equals(childName))
						childNode.getFirstChild().setNodeValue(user);
					else if("password".equals(childName))
						childNode.getFirstChild().setNodeValue(password);
				}
			}
			
			nodeList = xmlDoc.getElementsByTagName("program");
			databaseList = nodeList.item(0).getChildNodes();
			for(int i = 0, len = databaseList.getLength(); i < len; i++)
			{
				Node childNode = databaseList.item(i);
				if (childNode instanceof Element) 
				{  
					String childName = childNode.getNodeName();
					if("paging".equals(childName))
					{
						childNode.getFirstChild().setNodeValue(paging);
						break;
					}
				}
			}

//真正持久化的代码
			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer t = factory.newTransformer();
			t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			DOMSource source =  new DOMSource(xmlDoc); 
			StreamResult result = new StreamResult(new File("setting.xml"));
			t.transform(source, result);



2、利用dom4j:
(1)读文件

			SAXReader reader = new SAXReader();
			Document xmlDoc = reader.read(new File("setting.xml"));
			Element root = xmlDoc.getRootElement();
			List<Element> properties = root.elements("database");
			for(Element property : properties)
			{
				Element useSqlE = property.element("use_sql");
				useSql = useSqlE.getText();
				
				Element dialectE = property.element("dialect");
				for(Iterator<Element> iter = dialectE.elements().iterator(); iter.hasNext();)
				{
					Element e = iter.next();
					dialect.put(e.getName(), e.getText());
				}
				
				Element driverE = property.element("driver");
				driver = driverE.getText();
				

				Element urlE = property.element("url");
				url = urlE.getText();
				
				
				Element userE = property.element("user");
				user = userE.getText();

				Element passwordE = property.element("password");
				password = passwordE.getText();
			}
			
			properties = root.elements("program");
			for(Element property : properties)
			{
				Element pagingE = property.element("paging");
				paging = pagingE.getText();
				String name = property.getName();
				
			}

(2)写文件:

			SAXReader reader = new RAXReader();
<span style="white-space:pre">			</span>Document xmlDoc = reader.read(new File("setting.xml"));
			Element root = xmlDoc.getRootElement();
			List<Element> properties = root.elements("database");
			for(Element property : properties)
			{
				Element useSqlE = property.element("use_sql");
				useSqlE.setText(useSql);
				
				
				Element driverE = property.element("driver");
				driverE.setText(getDriver(useSql));
				

				Element urlE = property.element("url");
				urlE.setText(url);
				
				
				Element userE = property.element("user");
				userE.setText(user);

				Element passwordE = property.element("password");
				passwordE.setText(password);
				
			}
			
			properties = root.elements("program");
			for(Element property : properties)
			{
				String name = property.getName();
				if("paging".equals(name))
					property.setText(paging);
			}

//持久化
<span style="white-space:pre">			XMLWriter </span>writer = new XMLWriter(new FileWriter("setting.xml"));
<span style="white-space:pre">			</span>writer.write(xmlDoc);



补充:
如果标签带有属性,如下xml

<span style="color:#333333;"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
		<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="hibernate.connection.url">(DESCRIPTION=(LOAD_BALANCE=yes)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.3)(PORT=1521)))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=wait)))</property>
		<property name="hibernate.connection.username">system</property>
		<property name="hibernate.connection.password">Ze25506065</property>
		<property name="hibernate.cache.use_query_cache">false</property>
		<property name="hibernate.cache.use_second_level_cache">false</property>
		<property name="hibernate.show_sql">true</property>
	</session-factory>
</hibernate-configuration></span>

jdk读:
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = dbf.newDocumentBuilder();
			xmlDoc = builder.parse("src\\hibernate.cfg.xml");
			NodeList nodeList = xmlDoc.getElementsByTagName("session-factory");
			NodeList databaseList = nodeList.item(0).getChildNodes();
			for(int i = 0, len = databaseList.getLength(); i < len; i++)
			{
				Node childNode = databaseList.item(i);
				if (childNode instanceof Element) 
				{  
				
					String childName = ((Element)childNode).getAttribute("name");
					if("hibernate.dialect".equals(childName))
						childNode.getFirstChild().setNodeValue(dialect.get(useSql));
					else if("hibernate.connection.driver_class".equals(childName))
						childNode.getFirstChild().setNodeValue(driver);
					else if("hibernate.connection.url".equals(childName))
						childNode.getFirstChild().setNodeValue(url);
					else if("hibernate.connection.username".equals(childName))
						childNode.getFirstChild().setNodeValue(user);
					else if("hibernate.connection.password".equals(childName))
						childNode.getFirstChild().setNodeValue(password);
				}
			}

dom4j写:

			SAXReader reader = new SAXReader();
			Document xmlDoc = reader.read(new File("src\\hibernate.cfg.xml"));
			List<Element> properties = root.elements("session-factory");
			for(Element property : properties)
			{
				List<Element> list = property.elements();
				for(Iterator<Element> iter = list.iterator(); iter.hasNext();)
				{
					Element e = iter.next();
					String name = e.attributeValue("name");
					if("hibernate.dialect".equals(name))
						e.setText(dialect.get(useSql));
					else if("hibernate.connection.driver_class".equals(name))
						e.setText(driver);
					else if("hibernate.connection.url".equals(name))
						e.setText(url);
					else if("hibernate.connection.username".equals(name))
						e.setText(user);
					else if("hibernate.connection.password".equals(name))
						e.setText(password);
				}
			}


 
 


读写都差不多,写就是设置标签的值在写入文件
注意:
用jdk写入xml会改变xml的头标签,至于解决方法我没探究,而dom4j就不会改写头标签

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值