Related readings:
Use Ajax to upload files and other parameters (java development)
1. XML file:
What is XML? XML generally refers to an extensible markup language, a subset of standard general markup languages, and is a markup language used to mark electronic files to make them structural.
2. Advantages of XML files:
1) The content and structure of XML documents are completely separated.
2) Strong interoperability.
3) Standardize and unify.
4) Supports multiple encodings.
5) Strong scalability.
3. How to parse XML documents:
XML parsing XML documents in different languages are the same, but the implementation syntax is different. There are two basic parsing methods. One is the SAX method, which is parsing step by step in the order of XML files. Another analytical method is the DOM method, and the key to the DOM method is the node. There are also DOM4J, JDOM and other methods. This article introduces the DOM and DOM4J methods and the method of encapsulating them into a tool class to read XML documents.
4.XML Documentation:
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 San</name> <course>JavaSE</course> <score>100</score> </student> <student id="22"> <name>Li Si</name> <course>Oracle</course> <score>98</score> </student> </students>
5.DoM parsing XML
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { //1. Create DOM parser factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //2. Create DOM parser from the DOM parser factory DocumentBuilder db = dbf.newDocumentBuilder(); //3. Parses the document from the DOM parser to generate the DOM tree Document doc = db.parse("scores.xml"); //4. Parses the DOM tree and obtains 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 Get all child elements in scores student NodeList studentList = scoresNode.getChildNodes(); System.out.println(studentList.getLength()); //4.3 Process each student for(int i=0;i<studentList.getLength(); i++){ Node stuNode = studentList.item(i); //System.out.println(stuNode.getNodeType()); //The attribute id of the output element if(stuNode.getNodeType()==Node.ELEMENT_NODE){ Element elem =(Element)stuNode; String id= elem.getAttribute("id"); System.out.println("id------>"+id); } //The child elements of the output 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();//Text is a child of an element, so you need to getFirstChild String value = ncs.getTextContent(); System.out.println(name+"----->"+value); } } System.out.println(); } }6. DOM4J method parsing XML documents:
public static void main(String[] args) throws DocumentException { //Use dom4j to parse scores2.xml, generate dom tree SAXReader reader = new SAXReader(); Document doc = reader.read(new File("scores.xml")); //Get root node: students Element root = doc.getRootElement(); //Get all child nodes of students: student Iterator<Element> it = root.elementIterator(); //Train each student while(it.hasNext()){ //Get each student Element stuElem =it.next(); //System.out.println(stuElem); //Output student's 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 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 is the way I use it during the development process.
7.1 What are properties files:
7.1.1 Structurally:
.xml files are mainly tree files.
The .properties file mainly exists in the form of key-value key-value pairs.
7.1.2 From a flexible perspective:
.xml files are more flexible than .properties files.
7.1.3 From a convenient point of view:
The .properties file is easier to configure than the .xml file.
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 Your own properties documentation:
I created a path.properties file in my own project, which is used to store the path I will use, and stored in the form of name = value. For example:
realPath = D:/file/
7.3 Parses 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 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 only need to attach a value to the DATABASE_CONFIG_FILE property, which is the name of our .properties file. When using it, we can directly use the class name. getProperty(“realPath”); to get the content with the key in the .properties file that is realPath.
The above is the method of reading XML and properties configuration files in Java development introduced to you 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 reply to you in time!