I have introduced XML files in a previous article "Manipulating xml files with dom4j" , as well as manipulating xml files with dom4j. In fact, java has an extension package ( javax.xml ) that also provides a method for parsing xml. I will introduce the case next.
First, define the element rules (user.xsd) inside the xml file:
<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://www.itszt2.com" xmlns="http://www.itszt2.com"> <xs:element name="用户" type="type_user"></xs:element> <xs:complexType name="type_user"> <xs:sequence> <xs:element name="姓名" type="type_xm"></xs:element> <xs:element name="年龄" type="type_nl"></xs:element> <xs:element name="性别" type="type_xb" minOccurs="1" maxOccurs="999999999"></xs:element> <xs:element name="工资" type="type_gz"> </xs:element> <xs:element name="出生日期" type="xs:date"></xs:element> <xs:element name="爱好" type="type_hbs"></xs:element> </xs:sequence> </xs:complexType> <!-- Define the type of name --> <xs:simpleType name="type_xm"> <xs:restriction base="xs:string"> <xs:pattern value="\w{2,10}"/> </xs:restriction> </xs:simpleType> <!-- define the type of age --> <xs:simpleType name="type_nl"> <xs:restriction base="xs:integer"> <xs:minInclusive value="0"></xs:minInclusive> <xs:maxInclusive value="100"></xs:maxInclusive> </xs:restriction> </xs:simpleType> <!-- define gender type --> <xs:simpleType name="type_xb"> <xs:restriction base="xs:string"> <xs:enumeration value="男"/> <xs:enumeration value="女"/> </xs:restriction> </xs:simpleType> <!-- Define salary attribute; set content type in complex type, and attribute --> <xs:complexType name="type_gz"> <xs:simpleContent> <xs:extension base='xs:decimal'> <xs:attribute name='单位' type='xs:string' use="required" default="元" /> </xs:extension> </xs:simpleContent> </xs:complexType> <!--Define hobby type--> <xs:simpleType name="type_hbs"> <xs:restriction base="xs:string"></xs:restriction> </xs:simpleType> </xs:schema>
Next, write an xml file (test1.xml):
<?xml version="1.0"?> <用户 xmlns="http://www.itszt2.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.itszt2.com user.xsd"> <name>Wang Er</name> <age>20</age> <gender>male</gender> <salary unit="yuan">123.45</salary> <date of birth>1999-10-10</date of birth> <hobby>Mountain climbing</hobby> </user>
Write another entity class User, so that after reading the information from the xml file, a User object is generated accordingly:
package com.itszt; import java.util.List; /** * Entity class */ public class User { private String username; private String usersex; private String userdate; private String usersalary; private int userage; private String userhbs; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUsersex() { return usersex; } public void setUsersex(String usersex) { this.usersex = usersex; } public String getUserdate() { return userdate; } public void setUserdate(String userdate) { this.userdate = userdate; } public String getUsersalary() { return usersalary; } public void setUsersalary (String usersalary) { this.usersalary = usersalary; } public int getUserage() { return userage; } public void setUserage(int userage) { this.userage = userage; } public String getUserhbs() { return userhbs; } public void setUserhbs(String userhbs) { this.userhbs = userhbs; } @Override public String toString() { return "User [username=" + username + ", usersex=" + usersex + ", userdate =" + userdate + ", usersalary =" + usersalary + ", userage=" + userage + ", userhbs=" + userhbs + "]"; } }
Write a servlet that makes the front page click on the link to access the servlet, thereby triggering the reading of the xml file and object operations:
package com.itszt; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Read xml file */ @WebServlet(name = "SAX2Servlet",urlPatterns = "/SAX2Servlet") public class SAX2Servlet extends HttpServlet { private ThreadLocal<String> qNameNow=new ThreadLocal<String>(); private ThreadLocal<User> userNow=new ThreadLocal<User>(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ //Factory mode, get the xml parser, and then read the stream from the xml file SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(new DefaultHandler(){ @Override public void startDocument() throws SAXException { super.startDocument(); System.out.println("Start parsing the entire xml document"); } @Override public void endDocument() throws SAXException { super.endDocument(); System.out.println("End parsing the entire xml document"); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); System.out.println("Start parsing element: "+qName); if("用户".equals(qName)){ userNow.set(new User()); } qNameNow.set(qName); if("工资".equals(qName)){ String dw = attributes.getValue("单位"); System.out.println("dw = " + dw); String num = attributes.getValue("num"); System.out.println("num = " + num); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); System.out.println("End parsing label: " + qName); if("用户".equals(qName)){ System.out.println("After parsing, get user: "+userNow.get()); } //After parsing a tag element, reset qNameNow qNameNow.set(""); } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); String value=new String(ch,start,length); System.out.println("Found a value: "+value); if("姓名".equals(qNameNow.get())){ userNow.get().setUsername(value); } if("年龄".equals(qNameNow.get())){ userNow.get().setUserage(Integer.parseInt(value)); } if("性别".equals(qNameNow.get())){ userNow.get().setUsersex(value); } if("Date of Birth".equals(qNameNow.get())){ userNow.get().setUserdate(value); } if("工资".equals(qNameNow.get().toString())){ userNow.get().setUsersalary(value); } if("爱好".equals(qNameNow.get())){ userNow.get().setUserhbs(value); } } }); //Initiate parsing String xmlPath = request.getServletContext().getRealPath("/test3/test1.xml"); reader.parse(xmlPath); }catch (Exception e){ e.printStackTrace (); } } }