相關閱讀:
1. XML文件:
什么是XML?XML一般是指可擴展標記語言,標準通用標記語言的子集,是一種用于標記電子文件使其具有結構性的標記語言。
2.XML文件的優點:
1)XML文檔內容和結構完全分離。
2)互操作性強。
3)規范統一。
4)支持多種編碼。
5)可擴展性強。
3.如何解析XML文檔:
XML在不同的語言中解析XML文檔都是一樣的,只不過實現的語法不一樣,基本的解析方式有兩種,一種是SAX方式,是按照XML文件的順序一步一步解析。另外一種的解析方式DOM方式,而DOM方式解析的關鍵就是節點。另外還有DOM4J、JDOM等方式。本文介紹的是DOM、DOM4J方式與封裝成一個工具類的方式來讀取XML文檔。
4.XML文檔:
scores.xml:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE students [ <!ELEMENT students (student+)> <!ELEMENT student (name,course,score)> <!ATTLIST student id CDATA #REQUIRED> <!ELEMENT name (#PCDATA)> <!ELEMENT course (#PCDATA)> <!ELEMENT score (#PCDATA)>]><students> <student id="11"> <name>張三</name> <course>JavaSE</course> <score>100</score> </student> <student id="22"> <name>李四</name> <course>Oracle</course> <score>98</score> </student> </students>
5.DOM方式解析XML
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { //1.創建DOM解析器工廠 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //2.由DOM解析器工廠創建DOM解析器 DocumentBuilder db = dbf.newDocumentBuilder(); //3.由DOM解析器解析文檔,生成DOM樹 Document doc = db.parse("scores.xml"); //4.解析DOM樹,獲取文檔內容(元素 屬性 文本) //4.1獲取根元素scores NodeList scoresList = doc.getChildNodes(); Node scoresNode = scoresList.item(1); System.out.println(scoresList.getLength()); //4.2獲取scores中所有的子元素student NodeList studentList = scoresNode.getChildNodes(); System.out.println(studentList.getLength()); //4.3對每個student進行處理 for(int i=0;i<studentList.getLength();i++){ Node stuNode = studentList.item(i); //System.out.println(stuNode.getNodeType()); //輸出元素的屬性 id if(stuNode.getNodeType()==Node.ELEMENT_NODE){ Element elem =(Element)stuNode; String id= elem.getAttribute("id"); System.out.println("id------>"+id); } //輸出元素的子元素 name course score NodeList ncsList = stuNode.getChildNodes(); //System.out.println(ncsList.getLength() ); for(int j=0;j<ncsList.getLength();j++){ Node ncs = ncsList.item(j); if(ncs.getNodeType() == Node.ELEMENT_NODE){ String name = ncs.getNodeName(); //String value = ncs.getFirstChild().getNodeValue();//文本是元素的子節點,所以要getFirstChild String value = ncs.getTextContent(); System.out.println(name+"----->"+value); } } System.out.println(); } }6.DOM4J方式解析XML文檔:
public static void main(String[] args) throws DocumentException { //使用dom4j解析scores2.xml,生成dom樹 SAXReader reader = new SAXReader(); Document doc = reader.read(new File("scores.xml")); //得到根節點:students Element root = doc.getRootElement(); //得到students的所有子節點:student Iterator<Element> it = root.elementIterator(); //處理每個student while(it.hasNext()){ //得到每個學生 Element stuElem =it.next(); //System.out.println(stuElem); //輸出學生的屬性:id List<Attribute> attrList = stuElem.attributes(); for(Attribute attr :attrList){ String name = attr.getName(); String value = attr.getValue(); System.out.println(name+"----->"+value); } //輸出學生的子元素:name,course,score Iterator <Element>it2 = stuElem.elementIterator(); while(it2.hasNext()){ Element elem = it2.next(); String name = elem.getName(); String text = elem.getText(); System.out.println(name+"----->"+text); } System.out.println(); } }當然,無論我們是使用那種方式解析XML的,都需要導入jar包(千萬不要忘記)。
7.我自己的方式:
在實際開發的工程中,我們要善于使用工具類,將我們反復使用的功能封裝成一個工具類,所以,下面的方式就是我在開發的過程中使用的方式.
7.1什么是properties文件:
7.1.1 從結構上講:
.xml文件主要是樹形文件。
.properties文件主要是以key-value鍵值對的形式存在
7.1.2 從靈活的角度來說:
.xml文件要比.properties文件的靈活讀更高一些。
7.1.3 從便捷的角度來說:
.properties文件比.xml文件配置更加簡單。
7.1.4 從應用程度上來說:
.properties文件比較適合于小型簡單的項目,因為.xml更加靈活。
7.2自己的properties文檔:
在我自己的項目中創建了一個path.properties文件,里面用來存放我即將使用的路徑,以名字=值的方式存放。例如:
realPath = D:/file/
7.3 解析自己的.properties文件:
public class PropertiesUtil { private static PropertiesUtil manager = null; private static Object managerLock = new Object(); private Object propertiesLock = new Object(); private static String DATABASE_CONFIG_FILE = "/path.properties"; private Properties properties = null; public static PropertiesUtil getInstance() { if (manager == null) { synchronized (managerLock) { if (manager == null) { manager = new PropertiesUtil(); } } } return manager; } private PropertiesUtil() { } public static String getProperty(String name) { return getInstance()._getProperty(name); } private String _getProperty(String name) { initProperty(); String property = properties.getProperty(name); if (property == null) { return ""; } else { return property.trim(); } } public static Enumeration<?> propertyNames() { return getInstance()._propertyNames(); } private Enumeration<?> _propertyNames() { initProperty(); return properties.propertyNames(); } private void initProperty() { if (properties == null) { synchronized (propertiesLock) { if (properties == null) { loadProperties(); } } } } private void loadProperties() { properties = new Properties(); InputStream in = null; try { in = getClass().getResourceAsStream(DATABASE_CONFIG_FILE); properties.load(in); } catch (Exception e) { System.err .println("Error reading conf properties in PropertiesUtil.loadProps() " + e); e.printStackTrace(); } finally { try { in.close(); } catch (Exception e) { } } } /** * 提供配置文件路徑 * * @param filePath * @return */ public Properties loadProperties(String filePath) { Properties properties = new Properties(); InputStream in = null; try { in = getClass().getResourceAsStream(filePath); properties.load(in); } catch (Exception e) { System.err .println("Error reading conf properties in PropertiesUtil.loadProperties() " + e); e.printStackTrace(); } finally { try { in.close(); } catch (Exception e) { } } return properties; }}當我們使用之前,我們只需要給 DATABASE_CONFIG_FILE 屬性附上值,就是我們.properties文件的名稱,當使用的時候,我們就可以直接使用類名. getProperty(“realPath”);的方式就可以獲取到在.properties文件中的key為realPath的內容。
以上所述是小編給大家介紹的Java開發中讀取XML與properties配置文件的方法,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
新聞熱點
疑難解答