当前位置:网站首页>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 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); } }
边栏推荐
- SolidWorks工程图中添加中心线和中心符号线的办法
- Postman interface test II
- Some thoughts on the testing work in the process of R & D
- STM32产品介绍
- China's first electronic audio category "Yamano electronic audio" digital collection is on sale!
- [ORM framework]
- C logging method
- AHB bus in stm32_ Apb2 bus_ Apb1 bus what are these
- Become a "founder" and make reading a habit
- ES6中的函數進階學習
猜你喜欢
arcgis操作:dwg数据转为shp数据
ORM -- query type, association query
【acwing】789. Range of numbers (binary basis)
中国首款电音音频类“山野电音”数藏发售来了!
HAL库配置通用定时器TIM触发ADC采样,然后DMA搬运到内存空间。
Introduction to energy Router: Architecture and functions for energy Internet
Programming features of ISP, IAP, ICP, JTAG and SWD
Programming features of ISP, IAP, ICP, JTAG and SWD
Weekly recommended short videos: what are the functions of L2 that we often use in daily life?
China's first electronic audio category "Yamano electronic audio" digital collection is on sale!
随机推荐
SQLyog数据库怎么取消自动保存更改
Why are social portals rarely provided in real estate o2o applications?
Mongodb creates an implicit database as an exercise
【学习笔记-李宏毅】GAN(生成对抗网络)全系列(一)
[learning notes - Li Hongyi] Gan (generation of confrontation network) full series (I)
Google Colab装载Google Drive(Google Colab中使用Google Drive)
China's first electronic audio category "Yamano electronic audio" digital collection is on sale!
Chris Lattner, père de llvm: Pourquoi reconstruire le logiciel d'infrastructure ai
【acwing】786. Number k
单片机(MCU)最强科普(万字总结,值得收藏)
UnityWebRequest基础使用之下载文本、图片、AB包
How to cancel automatic saving of changes in sqlyog database
PDF文档签名指南
Google colab loads Google drive (Google drive is used in Google colab)
The combination of over clause and aggregate function in SQL Server
学习记录——高精度加法和乘法
Arcgis操作: 批量修改属性表
Official media attention! The list of top 100 domestic digital collection platforms was released, and the industry accelerated the healthy development of compliance
Introduction to uboot
ES6中的函数进阶学习