当前位置:网站首页>XML configuration file parsing and modeling
XML configuration file parsing and modeling
2022-07-07 10:19:00 【Bugxiu_ fu】
Catalog
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 elements2, 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); } }
边栏推荐
- Postman interface test III
- AHB bus in stm32_ Apb2 bus_ Apb1 bus what are these
- LeetCode 练习——113. 路径总和 II
- Encrypt and decrypt stored procedures (SQL 2008/sql 2012)
- Wallys/IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL CONCURRENT
- 一文讲解单片机、ARM、MUC、DSP、FPGA、嵌入式错综复杂的关系
- Some test points about coupon test
- Using keras in tensorflow to build convolutional neural network
- LLVM之父Chris Lattner:為什麼我們要重建AI基礎設施軟件
- Why does the starting service report an error when installing MySQL? (operating system Windows)
猜你喜欢

The Hal library is configured with a general timer Tim to trigger ADC sampling, and then DMA is moved to the memory space.

PDF文档签名指南

ORM -- logical relation and & or; Sort operation, update record operation, delete record operation

每周推荐短视频:L2级有哪些我们日常中经常会用到的功能?

Programming features of ISP, IAP, ICP, JTAG and SWD

Wallys/IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL CONCURRENT

Agile course training

STM32 ADC and DMA

Chris Lattner, père de llvm: Pourquoi reconstruire le logiciel d'infrastructure ai
![[ORM framework]](/img/72/13eef38fc14d85978f828584e689a0.png)
[ORM framework]
随机推荐
Deconvolution popular detailed analysis and nn Convtranspose2d important parameter interpretation
ORM--分组查询,聚合查询,查询集QuerySet对象特性
IO模型复习
The method of word automatically generating directory
Interface test
网上可以开炒股账户吗安全吗
Bean operation domain and life cycle
Vs code specifies the extension installation location
柏拉图和他的三个弟子的故事:如何寻找幸福?如何寻找理想伴侣?
IPv4套接字地址结构
Official media attention! The list of top 100 domestic digital collection platforms was released, and the industry accelerated the healthy development of compliance
Postman interface test II
2022.7.6DAY598
ES6中的函数进阶学习
Download Text, pictures and ab packages used by unitywebrequest Foundation
电表远程抄表拉合闸操作命令指令
Smart city construction based on GIS 3D visualization technology
2022.7.4DAY596
The request object parses the request body and request header parameters
ORM模型--关联字段,抽象模型类


