Method for reading XML and properties configuration files in Java development

  • 2020-05-27 05:45:06
  • OfStack

Related reading:

Upload files and other parameters using Ajax (java development)

1. XML file:

What is XML? XML1 generally refers to the extensible markup language, a subset of the standard general-purpose markup language, which is a markup language used to tag electronic files for structural purposes.

2. Advantages of XML file:

1) the content and structure of XML document are completely separated.
2) strong interoperability.
3) standard system 1.
4) multiple codes are supported.
5) strong scalability.

3. How to parse XML documents:

XML parses XML documents in different languages in the same way, but the syntax of the implementation is not the same. There are two basic parsing methods, one is SAX, which is parsed step by step according to the order of XML files. The other one is DOM, and the key of DOM is the node. In addition, there are also DOM4J, JDOM and other ways. This article describes the DOM, DOM4J and the way to read XML documents wrapped into a single tool class.

4. XML documents:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE students [
 <!ELEMENT students (student+)>
 <!ELEMENT student (name,course,score)>
 <!ELEMENT name (#PCDATA)>
 <!ELEMENT course (#PCDATA)>
 <!ELEMENT score (#PCDATA)>
 <student id="11"> 
  <name> zhang 3</name> 
 <student id="22">  
  <name> li 4</name>

5.DOM mode analyzes XML

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
  //1. create DOM Parser factory 
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  //2. by DOM Parser factory creation DOM The parser 
  DocumentBuilder db = dbf.newDocumentBuilder();
  //3. by DOM The parser parses the document and generates it DOM The tree 
  Document doc = db.parse("scores.xml");
  //4. parsing DOM Tree, get the document content (element   attribute   Text) 
  //4.1 Get the root element scores
  NodeList scoresList = doc.getChildNodes();
  Node scoresNode = scoresList.item(1);
  //4.2 To obtain scores All the child elements in student
  NodeList studentList = scoresNode.getChildNodes();
  //4.3 For each student For processing 
  for(int i=0;i<studentList.getLength();i++){
   Node stuNode = studentList.item(i);
   // Output the attributes of the element  id
    Element elem =(Element)stuNode;
    String id= elem.getAttribute("id");
   // Output the children of the element  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();// The text is a child of the element, so getFirstChild
      String value = ncs.getTextContent();

6.DOM4J parsing of XML documents:

 public static void main(String[] args) throws DocumentException {
  // use dom4j parsing scores2.xml, generate dom The tree 
  SAXReader reader = new SAXReader();
  Document doc = File("scores.xml"));  
  // Get the root node: students
  Element root = doc.getRootElement();  
  // get students Of all child nodes: student
  Iterator<Element> it = root.elementIterator(); 
  // Handle each student
   // Get every student 
   Element stuElem;
   // Output student attributes: id
   List<Attribute> attrList = stuElem.attributes();
   for(Attribute attr :attrList){
    String name = attr.getName();
    String value = attr.getValue();
   // Output student's child elements: name . course . score
   Iterator <Element>it2 = stuElem.elementIterator();
    Element elem =;
    String name = elem.getName();
    String text = elem.getText();

Of course, no matter which way we parse XML, we need to import the jar package (don't forget).

7. My own way:

In the actual development project, we should be good at using the tool class and encapsulate the functions we repeatedly use into a tool class. Therefore, the following way is the way I used in the development process.

7.1 what is properties file:

7.1.1 structurally speaking:

.xml files are mainly tree files. file is mainly in the form of key-value key-value pairs

7.1.2 from a flexible perspective:

The.xml file is a bit more flexible than file.

7.1.3 from the perspective of convenience: file is simpler to configure than the.xml file.

7.1.4 in terms of application degree: file is better suited for small and simple projects because.xml is more flexible.

7.2 own properties documents:

In my own project, I created an file to hold the path I was going to use, in the form of a name = value. Such as:

realPath = D:/file/

7.3 parse your 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 = "/";
 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) {
  String property = properties.getProperty(name);
  if (property == null) {
   return "";
  } else {
   return property.trim();
 public static Enumeration<?> propertyNames() {
  return getInstance()._propertyNames();
 private Enumeration<?> _propertyNames() {
  return properties.propertyNames();
 private void initProperty() {
  if (properties == null) {
   synchronized (propertiesLock) {
    if (properties == null) {
 private void loadProperties() {
  properties = new Properties();
  InputStream in = null;
  try {
   in = getClass().getResourceAsStream(DATABASE_CONFIG_FILE);
  } catch (Exception e) {
     .println("Error reading conf properties in PropertiesUtil.loadProps() "
       + e);
  } finally {
   try {
   } catch (Exception e) {
  *  Provide the configuration file path 
  * @param filePath
  * @return
 public Properties loadProperties(String filePath) {
  Properties properties = new Properties();
  InputStream in = null;
  try {
   in = getClass().getResourceAsStream(filePath);
  } catch (Exception e) {
     .println("Error reading conf properties in PropertiesUtil.loadProperties() "
       + e);
  } finally {
   try {
   } catch (Exception e) {
  return properties;

Before we use it, we just need to give it DATABASE_CONFIG_FILE Property, which is the name of file, when used, we can use the class name directly. getProperty(“realPath”); The content of key is realPath in file.

The above is this site to introduce you Java development read XML and properties configuration file method, I hope to help you, if you have any questions welcome to give me a message, this site will timely reply to you!

Related articles: