Home > Java > javaTutorial > How to read XML and properties configuration files in Java development

How to read XML and properties configuration files in Java development

高洛峰
Release: 2017-01-12 10:27:03
Original
1672 people have browsed it

Related reading:

Using Ajax to upload files and other parameters (java development)

1. XML file:

What is XML? XML generally refers to Extensible Markup Language, a subset of Standard Universal Markup Language. It is a markup language used to mark electronic documents to make them structural.

2. Advantages of XML files:

1) The content and structure of XML documents are completely separated.
2) Strong interoperability.
3) Standardization and unification.
4) Support multiple encodings.
5) Strong scalability.

3. How to parse XML documents:

XML parses XML documents in different languages ​​​​the same, but the syntax implemented is different. There are two basic parsing methods, one The first is the SAX method, which parses the XML file step by step in the order of the XML file. Another parsing method is the DOM method, and the key to DOM parsing is the node. There are also DOM4J, JDOM and other methods. This article introduces the DOM, DOM4J method and the method of encapsulating it into a tool class to read XML documents.

4.XML document:

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>
Copy after login

5.DOM parsing 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();
  }
 }
Copy after login

6.DOM4J way to parse XML documents:

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();
 }
}
Copy after login

Of course, no matter what kind of To parse XML, you need to import the jar package (don’t forget it).

7. My own way:

In actual development projects, we must be good at using tool classes and encapsulate the functions we use repeatedly into a tool class. Therefore, the following method This is the method I use during the development process.

7.1 What is a properties file:

7.1.1 Structurally speaking:

.xml file is mainly in tree shape document.
.properties files mainly exist in the form of key-value pairs

7.1.2 From a flexible perspective:

.xml files are more flexible than .properties files Read higher.

7.1.3 From a convenience perspective:

.properties files are simpler to configure than .xml files.

7.1.4 From the perspective of application:

.properties files are more suitable for small and simple projects because .xml is more flexible.

7.2 My own properties document:

I created a path.properties file in my own project, which is used to store the path I am about to use, stored in the form of name = value. For example:

realPath = D:/file/

7.3 Parse your own .properties file:

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;
 }
}
Copy after login

When we Before use, we only need to attach a value to the DATABASE_CONFIG_FILE attribute, which is the name of our .properties file. When used, we can directly use the class name. getProperty("realPath"); to obtain the .properties The key in the file is the content of realPath.

The above is the method of reading XML and properties configuration files in Java development introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will promptly Reply to everyone!

For more articles related to methods of reading XML and properties configuration files in Java development, please pay attention to the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template