当前位置:网站首页>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); } }
边栏推荐
- 【学习笔记-李宏毅】GAN(生成对抗网络)全系列(一)
- Pdf document signature Guide
- The landing practice of ByteDance kitex in SEMA e-commerce scene
- Inno setup packaging and signing Guide
- Introduction to uboot
- LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
- ORM--逻辑关系与&或;排序操作,更新记录操作,删除记录操作
- The physical meaning of imaginary number J
- Wallys/IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL CONCURRENT
- ORM -- database addition, deletion, modification and query operation logic
猜你喜欢
嵌入式背景知识-芯片
SolidWorks工程图中添加中心线和中心符号线的办法
STM32中AHB总线_APB2总线_APB1总线这些是什么
LLVM之父Chris Lattner:為什麼我們要重建AI基礎設施軟件
Encrypt and decrypt stored procedures (SQL 2008/sql 2012)
“十二星座女神降临”全新活动推出
ORM模型--数据记录的创建操作,查询操作
Introduction to energy Router: Architecture and functions for energy Internet
一文讲解单片机、ARM、MUC、DSP、FPGA、嵌入式错综复杂的关系
基于gis三维可视化技术的智慧城市建设
随机推荐
The landing practice of ByteDance kitex in SEMA e-commerce scene
Weekly recommended short videos: what are the functions of L2 that we often use in daily life?
ORM -- grouping query, aggregation query, query set queryset object properties
ES6中的函數進階學習
【学习笔记-李宏毅】GAN(生成对抗网络)全系列(一)
ORM--逻辑关系与&或;排序操作,更新记录操作,删除记录操作
STM32 product introduction
web3.0系列之分布式存储IPFS
串口通讯继电器-modbus通信上位机调试软件工具项目开发案例
AHB bus in stm32_ Apb2 bus_ Apb1 bus what are these
Or in SQL, what scenarios will lead to full table scanning
A wave of open source notebooks is coming
搭建物联网硬件通信技术几种方案
LeetCode 练习——113. 路径总和 II
PDF文档签名指南
ES6中的函数进阶学习
UnityWebRequest基础使用之下载文本、图片、AB包
嵌入式背景知识-芯片
Leetcode exercise - 113 Path sum II
Postman interface test I