[Java] 解析Xml配置文件

1、解析方法


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public
static Map<String, String> parseXml(String xmlPath) { /** * 以解析xml中的dataSource標籤中的url username password屬性值爲例 */ String url = ""; String username = ""; String password = ""; Map<String, String> map = new HashMap<String, String>(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); /** * xmlPath爲待解析xml文件的路徑 */ Document document = db.parse(xmlPath); /** * 此處的dataSource爲標籤名,即獲取該xml文件下所有的dataSource標籤 */ NodeList nodeList = document.getElementsByTagName("dataSource"); /** * 遍歷標籤(xml文件內dataSorce標籤只有一個) */ for (int i = 0; i < nodeList.getLength(); i++) { Node item = nodeList.item(i); /** * 獲取item標籤的屬性字段 */ NamedNodeMap attributes = item.getAttributes(); /** * 遍歷該標籤的所有屬性 */ for (int j = 0; j < attributes.getLength(); j++) { /** * 此處就是獲取指定屬性的值 */ if ("dbUrl".equals(attributes.item(j).getNodeName())) { url = attributes.item(j).getNodeValue(); } else if ("userName".equals(attributes.item(j).getNodeName())) { username = attributes.item(j).getNodeValue(); } else if ("passWord".equals(attributes.item(j).getNodeName())) { password = attributes.item(j).getNodeValue(); } } } map.put("url", url); map.put("username", username); map.put("password", password); } catch (Exception e) { e.printStackTrace(); } return map; }

2、測試xml的內容

<?xml version="1.0" encoding="gbk"?>
<config>
    <dataSource name="default" desc="彩票數據源" 
                 driverName="com.mysql.jdbc.Driver" 
                 dbUrl="jdbc:mysql://localhost:3306/icaipiao?useUnicode=true&amp;characterEncoding=UTF-8&amp;useOldAliasMetadataBehavior=true"
                 userName="root" passWord="123456"  
                 checkSql="select 1+2 FROM dual" interval="1"
                 startNum="2" maxNum="10"  maxCallNum="100000"
                 serverType="mysql" dbUrlBak="">
    </dataSource>
    <map file="C://1.txt"></map>
</config>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章