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:

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> zhang 3</name> 
  <course>JavaSE</course>
  <score>100</score>
 </student>
 <student id="22">  
  <name> li 4</name>
  <course>Oracle</course>
  <score>98</score>
 </student> 
</students>

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);
  System.out.println(scoresList.getLength());
  //4.2 To obtain scores All the child elements in student
  NodeList studentList = scoresNode.getChildNodes();
  System.out.println(studentList.getLength());
  //4.3 For each student For processing 
  for(int i=0;i<studentList.getLength();i++){
   Node stuNode = studentList.item(i);
   //System.out.println(stuNode.getNodeType());
   // Output the attributes of the element  id
   if(stuNode.getNodeType()==Node.ELEMENT_NODE){
    Element elem =(Element)stuNode;
    String id= elem.getAttribute("id");
    System.out.println("id------>"+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();
      System.out.println(name+"----->"+value);
    }
   }
   System.out.println();
  }
 }

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 = reader.read(new 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
  while(it.hasNext()){
   // Get every student 
   Element stuElem =it.next();
   //System.out.println(stuElem);
   // Output student attributes: id
   List<Attribute> attrList = stuElem.attributes();
   for(Attribute attr :attrList){
    String name = attr.getName();
    String value = attr.getValue();
    System.out.println(name+"----->"+value);
   }
   // Output student's child elements: 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();
  } 
 }

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.
The.properties 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 the.properties file.

7.1.3 from the perspective of convenience:

The.properties file is simpler to configure than the.xml file.

7.1.4 in terms of application degree:

The.properties 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 path.properties 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 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) {
   }
  }
 }
 /**
  *  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);
   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;
 }
}

Before we use it, we just need to give it DATABASE_CONFIG_FILE Property, which is the name of our.properties file, when used, we can use the class name directly. getProperty(“realPath”); The content of key is realPath in the.properties 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: