当前位置:网站首页>XML configuration file parsing and modeling

XML configuration file parsing and modeling

2022-07-07 10:19:00 Bugxiu_ fu

Catalog

What is? xml?

xml The role of :

One ,XML Element definition syntax

Two ,XML Attribute definition syntax

Model and parse to memory module


Today, I will share with you xml Parsing and reading configuration files , I hope it can help you guys .

What is? xml?

It's markup language , Write according to the prescribed grammar xml file , Can be parsed successfully .

xml The role of :

1, Data interaction ( Data transmission across languages )

2, Configuration

Study xml Purpose : Customize MVC Manual configuration required xml.

The standard xml What is the format ?

1, There is only one root element ( First response )

2,,xml Labels are case sensitive

3, Use nesting correctly ( Don't mess up )

4, Use legal tag name ( Cannot use keyword ) And properties ( It has well-defined properties , You can't DIY)

Code to be defined

<persons>
    <person pid="p1" sex=" male " qq="aaa" parent="p2">
        <name> Zhang Xiaoming </name>
        <age>10</age>
        <contact>
            <phone>1234567</phone>
        </contact>
        <br/>
    </person>
    <person pid="p2">
        <name> Zhang Daming </name>
        <age>35</age>
        <contact>
            <email>[email protected]</email>
        </contact>
    </person>
</persons>

One ,XML Element definition syntax

xml Before joining, state at the top :

<!DOCTYPE rott[]>

1, Classification syntax of elements

//rott   For the root element 
​
<!ELEMENT element-name Empty>   Empty elements 
​
<!ELEMENT element-name(#PCDATA)>   Text elements 
​
<!ELEMENT element-name(e1,e2,e3..)>      Mixed elements 

2, Frequency grammar

0 or 1:?

0~N:*

1~N:+

example

<!DOCTYPE persons[  
<!ELEMENT persons (person+)>
<!ELEMENT person (name,age,contact,br*)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT contact (phone|email)>
<!ELEMENT br EMPTY>
]>

Two ,XML Attribute definition syntax

xml Before joining, state at the top :

<!ATTLIST element-name att_name type desc>

1, Attribute type syntax

ID( Number )、CDATA( Text content )、IDREF( Parent label )、reference,( male | Woman )

#REQUIRED: Required #IMPLIED: optional

‘ The default value is ’: Only type by ( male , Woman ) Type ,dese The default value method can be used

example

<!ATTLIST person
pid ID #REQUIRED 
sex ( male | Woman ) ' Woman '
qq CDATA #IMPLIED
parent IDREF #IMPLIED
>

matters needing attention : The attribute definition code must be in the element definition code , in other words , The element definition code must contain the element definition code .

Read xml Case study

Need to use jar Bao explained in detail

beanutils Handle java Package of reflection mechanism

logging Package for processing log files

dom4j analysis xml Package of files

neat analysis xml Package of files

jstl jsp Tag library

conector load mysql Driver package

standard servert Process the requested package

Need to parse the read students.xml

<?xml version="1.0" encoding="UTF-8"?>
<students>
    <student sid="s001">
        <name> Xiao Ming </name>
    </student>
    <student sid="s002">
        <name> Xiaofang </name>
    </student>
    <student sid='s003'>
        <name> Xiao Wang </name>
    </student>
</students>

give the result as follows

The parsing code is as follows

public static void main(String[] args) throws Exception {
        InputStream in = Wordxml2Read.class.getResourceAsStream("/students.xml");// adopt Java Reflection mechanism acquisition IO flow 
        SAXReader reader = new SAXReader();// Instantiation xml Parser 
        Document doc = reader.read(in);// Read stream object , And use Document encapsulation 
        Element root = doc.getRootElement();// obtain Element The root node 
        
        List<Element> students = root.selectNodes("/students/student");// Get all attributes of multiple child nodes under the root node 
        for (Element student : students) {// Traverse all child nodes 
            String sid = student.attributeValue("sid");// adopt attributeValue() Get the child node attributes 
            System.out.println("sid="+sid);
                
            List<Element> name = student.selectNodes("name");
            for (Element names : name) {
                System.out.println(names.getText());
            }
        }
    //String name = student.selectSingleNode("name").getText();// Get a single node 
    }
}

Model and parse to memory module

What needs to be modeled config.xml Configure core files

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config[
	<!ELEMENT config (action*)>
	<!ELEMENT action (forward*)>
	<!ELEMENT forward EMPTY>
	<!ATTLIST action
	  path CDATA #REQUIRED
	  type CDATA #REQUIRED
	>
	<!ATTLIST forward
	  name CDATA #REQUIRED
	  path CDATA #REQUIRED
	  redirect (true|false) "false"
	>
]>
<config>
	<action path="/studentAction" type="org.lisen.mvc.action.StudentAction">
		<forward name="students" path="/students/studentList.jsp" redirect="false"/>
	</action>
	<action path="/studentAction01" type="org.lisen.mvc.action.StudentAction">
		<forward name="students01" path="/students/studentList.jsp" redirect="true"/>
	</action>
</config>

give the result as follows

configModel class

package mvc;

import java.util.HashMap;
import java.util.Map;

import Exception.ActionDuliplateDefinitionException;
import Exception.ActionNoFindException;

public class ConfigModel {

	Map<String,ActionModel> actionMap=new HashMap<String, ActionModel>();
	
	// obtain action Of path, Then save to the collection 
	public void addConfig(ActionModel action) {
		if(actionMap.containsKey(action.getPath())) {// If action Of path Value already exists , Just report an exception , because action The key is the only one 
			throw new ActionDuliplateDefinitionException("action path:" + action.getPath()+ "  Can't repeat ");
		}
		actionMap.put(action.getPath(), action);
	}
	// obtain xml in action Of path value 
	public ActionModel find(String path) {
		if(!actionMap.containsKey(path)) {//xml If action It doesn't contain path The abnormal 
			throw new ActionNoFindException("action path:"+path+" Can't find ");
		}
		return actionMap.get(path);
	}
}

ActionModel class

package mvc;

import java.util.HashMap;
import java.util.Map;

import Exception.ForwardDuliplateDefinitionException;
import Exception.ForwardNotFoundException;

public class ActionModel {
	
	String path;
	String type;
	
	Map<String, ForwardMeodel> forwardMap=new HashMap<String, ForwardMeodel>();
	
	
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	@Override
	public String toString() {
		return "ActionModel [path=" + path + ", type=" + type + "]";
	}
	// obtain forward Of path, Then save to the collection 
	public void addAction(ForwardMeodel forward) {
		System.out.println(forward);
		if(forwardMap.containsKey(forward.getName())) {// If forwardMap Of name Value already exists , Just report an exception , because forward The key is the only one 
			throw new ForwardDuliplateDefinitionException("forward name:"+forward.getName()+" Can't repeat ");
		}
		forwardMap.put(forward.getName(), forward);
	}
	// obtain xml in forward Of name value 
	public ForwardMeodel find(String name) {
		if(!forwardMap.containsKey(name)) {//xml If forward It doesn't contain name The abnormal 
			throw new ForwardNotFoundException("forward name:"+name+" non-existent ");
		}
		return forwardMap.get(name);
	}
	
}

ForwardMeodel class

package mvc;

public class ForwardMeodel {

	String name;
	String path;
	boolean redirect;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	
	public boolean isRedirect() {
		return redirect;
	}
	
	public void setRedirect(boolean redirect) {
		this.redirect = redirect;
	}
	
	public void setRedirect(String redirect) {
	if("true".equals(redirect) || "false".equals(redirect)) {
		this.redirect= Boolean.valueOf(redirect);
		}else {
			throw new RuntimeException(" attribute redirect The value of must be bits ture perhaps false");
		}
	}
	
	
	@Override
	public String toString() {
		return "ForwardMeodel [name=" + name + ", path=" + path + ", redirect=" + redirect + "]";
	}
	
	
}

Parse and generate ConfigModelFactory Model

package mvc;

import java.io.InputStream;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public final class ConfigModelFactory {

	private ConfigModelFactory() {}// The singleton pattern ( Hunger patterns in , There is only one example , Can't be instantiated )
	
	private static ConfigModel config=new ConfigModel();
	
	// Static code block , Execute only once when the class is loaded , It's done here config.xml File parsing and Config dependent 
	// Model building , In this way, it will only be parsed once in the whole system operation stage 
		static{
			try {
			InputStream is = ConfigModelFactory.class.getResourceAsStream("/config.xml");// obtain IO Stream object 
			SAXReader reader=new SAXReader();// Instantiation xml Parser 
			Document doc = reader.read(is);// Read and put Document file 
			Element root=doc.getRootElement();// obtain Element The root node 
			List<Element> Nodes = root.selectNodes("/config/action");// Get all the elements ( Under the root element )
			for (Element action : Nodes) {// Traversing child elements 
				String path = action.attributeValue("path");
				String type=action.attributeValue("type");// adopt attributeValue() Method to get the attribute text 

				ActionModel actionModel=new ActionModel();
				actionModel.setPath(path);// Set properties to ActionModel in 
				actionModel.setType(type);
				
				
			List<Element> forwards = action.selectNodes("forward");// Get all the elements ( Under the root element )
			for (Element f : forwards) {// Traversing child elements 
				String name = f.attributeValue("name");// adopt attributeValue() Method to get the attribute text 
				String fpath = f.attributeValue("path");
				String redirect = f.attributeValue("redirect");
				
				ForwardMeodel forwardMeodel=new ForwardMeodel();
				forwardMeodel.setName(name);// Set properties to ForwardMeodel in 
				forwardMeodel.setPath(fpath);
				forwardMeodel.setRedirect(redirect);
				
				actionModel.addAction(forwardMeodel);// take forwardMeodel Add to actionModel
			}
			
			config.addConfig(actionModel);// take actionModel Add to configMepdel
			}
		}catch(Exception e){
			throw new RuntimeException(e);// The abnormal information received is upward 
		}
		}
		
		// Get system's Config Configuration object 
		public static ConfigModel getConfig() {
			return config;
		}
		
		// Test code 
		public static void main(String[] args) {
			ConfigModel configModel = getConfig();
			ActionModel action = configModel.find("/studentAction");
			System.out.println(action);
			
			ForwardMeodel forward = action.find("students");
			System.out.println(forward);
			
		}
}

原网站

版权声明
本文为[Bugxiu_ fu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070721271123.html