Article directory
1, Overview of XML files
1. XML file
(1) Introduction
- Extensible markup language, a subset of standard general markup language, is a kind of markup language used to mark electronic documents to make them have structure. XML is designed to transfer data, not display it.
- XML files can be parsed directly using a parser (IE browser).
(2) Role
- For data storage
- For profile
(3) Basic grammar
① Document declaration
<?xml version="1.0" encoding="utf-8" standalone="no" ?>
- The document declaration must start with <? XML and end with? > with no space in the middle,? Means start or end;
- The document declaration must start from the 0 row and 0 column position of the document;
- xml indicates that the file is in xml format, and the file suffix is. xml;
- There are only two attributes in document declaration, format: attribute name = attribute value, attribute value must use "";
- Version specifies the version of the XML document. Required attribute, currently only version 1.0;
- Encoding specifies the encoding of the current document. Optional attribute, the default value is UTF-8;
- standlone indicates whether the file is independent, yes indicates yes, and no indicates No.
2. Sample XML file
<?xml version="1.0" encoding="utf-8" ?> < China > < Chongqing > < Jiangbei > Jiangbei < / Jiangbei > < Yubei > Yubei < / Yubei > < Chongqing > < Sichuan > < Chengdu > Chengdu < / Chengdu > < Nanchong > Nanchong < / Nanchong > < Sichuan > < China >
② Element and Tag
- Enclosed in angle brackets are elements (same as html, but all tag names can be customized)
- Element body can be written or not
- The element body can be text or other labels
- Element name:
Case sensitive
Cannot use space, colon special character
Starting with XML, XML, XML is not recommended - A well formatted xml document must have only one root element
③ attribute:
- Attributes are part of the element, written in angle brackets of the start tag, and multiple attributes are separated by spaces
- Property definition format: property name = property value, where property value must use single or double quotation marks
- An element can have 0-N attributes, but an attribute with the same name cannot appear in an element
- Property names cannot use special characters such as spaces, colons, and must start with a letter
Note 4
<! -- comment content -- >
Area CDATA
- Raw data, all the content as raw data.
- Syntax: <! [CDATA] [characters to translate] >
⑥ Escape character:
< | < | less than |
---|---|---|
> | > | greater than |
& | & | and |
' | ' | Single quotation mark |
" | " | Double quotation marks |
⑦ Instruction: import tag XML stylesheet
For example: introduce css file in an xml:
<?xml-stylesheet type="text/css" href="css file name.css" ?>
2, Constraints on XML files
1. Constraints overview
(1) Introduction
- Write xml files according to certain rules, and only fixed tags can be stored in the specified location.
(2) DTD constraints
<! Element root signature (data type or child label, if the label name is the same (label +)) > <! Element parent signature (in case of different child signatures, list directly, separated by commas) > <! Element subscript signature (ාpcdata) > Introduce DTD constraint: <! DOCTYPE root signature SYSYTEM "imported files" >
(3) Three DTD constraints
- Internal DTD, embed DTD inside XML document, only valid for current XML
- External DTD - local DTD. DTD documents are on the local system and used by the company's own projects
- External DTD - public DTD, DTD documents on the network, generally provided by the framework
2. DTD constraint example
xml file import constraints
① xml file
<?xml version="1.0" encoding="utf-8" standalone="no" ?> <! DOCTYPE informationsystem "users. DTD" > < information > < user > < name > Zhang San < / name > < gender > male < / gender > < age > 12 < / age > < user > < user 1> < name > Li Si < / name > < gender > female < / gender > < age > 23 < / age > < user 1> < information >
② dtd constraint file
<! Element information (user +) > <! Element user (name, gender, age) > < name of element (PCDATA) > <! Element gender (PCDATA) > <! Element age (PCDATA) >
By default, IE browser closes the verification file, which needs to be opened by script file:
- Create the ActiveXObject object in IE browser and use the control in its object (Microsoft.XMLDOM);
- Set the value of validateOnParse variable to false;
- Read the xml file to verify: load("xml file").
<html> <head> <script> var xmldom = new ActiveXObject("Microsoft.XMLDOM"); xmldom.validateOnParse = true; xmldom.load("users.xml"); //Output error reason and number of lines document.write(xmldom.parseError.reason+"<br />"); document.write(xmldom.parseError.line); </script> </head> <body> </body> </html>
3, Analysis of XML file
1. Overview of XML file parsing
(1) Introduction
There are three development packages for parsing xml files in java: JAXP Jdom dom4j, and the latter two can be combined into one.
2. DOM parsing
(1) Introduction
- DOM parsing method belongs to JAXP development package: DocumentBuilderFactory abstract class
- DOM parsing first parses all the contents of an xml file into memory, and then builds a Document tree in memory.
- The tag is resolved to Element, the attribute to attr, and the content to text, but whether the attribute or the tag or the text content will be resolved to Node node.
(2) Advantages and disadvantages
Advantages: the structure relationship between elements is preserved, and the operation of adding, deleting, modifying and querying can be performed, which is faster;
Disadvantages: when the XML document is too large, memory overflow may occur;
(3) DOM parsing process:
① Create a factory to parse xml files: DocumentBuilderFactory object;
② According to the acquired factory, we get the parser to parse xml documents: DocumentBuilder object;
③ Get the parser and start parsing the xml file: use the object call parse method to parse the xml document.
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("File path"));
④ Resolve node attribute name and value
Unknown number of nodes
Get a collection of all nodes Nodelist klist = document.getElementByTagName("node"); Use the for loop to traverse each node through the item() method Node node= list.item(i); And get all the attribute sets of the node NameNodeMap attrs = node.getAttribute(); Use the for loop to traverse the properties of a node through the item() method Node attr = attrs.item(j); Get property name attr.getNodeName(); Get property value attr.getNodeValue();
The following methods are available for only one ID attribute of the found book node, using cast
Element node= (Element) list.item(i); String attrValue = node.getAttribute("attribute name"); Get the attribute value of id attribute: attrValue;
⑤ Resolve child node name and value
Nodelist childNodes = node.getChildNodes(); Traverse childNodes to get the node name and value of each node, including spaces and line breaks Use for loop traversal Distinguish nodes of text type and element type by getNodeType(); childNodes.item(k).getNodeType() == Node.ELEMENT_NODE childNodes.item(k).getNodeName(); Get the node value of the child node You need to get the book child node first, and then get the node value of the child node's child node chileNodes.item(k).getFirstChild().getNodeValue();
The difference between getNodeValue() and getTextContent()
Of ChildNodes.item(i).getFirstChild().getNodeValue() and ChildNodes.item(i).getTextContent() Difference: when there are other child nodes in the child node, the latter can display the values of the child nodes. getTextContent() gets the text content (that is, the node value) in the node getNodeType() has text, element and attr If an Element wants to get a value, it must read its child node, which is considered as the child node of name by < name > content < / name >; Two methods: getFirstChild().getNodeName(); (get the child node and get the value) getTextContent(); (get content method)
⑥ Update the xml modified data in memory to a file, using Transformer().
//Write the modified data to the file TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer former = transFactory.newTransformer(); former.transform(new DOMSource(document), new StreamResult(new File(file)));
(4) DOM parsing add, delete, modify and query example
public class XMLDemo1 { public static void main(String[] args) throws Exception { XMLDemo1 xml1 = new XMLDemo1(); xml1.read1(); //xml1.read2(); //update() //delete() //add() } //Define a method to get the text content in the label (query) public void read() throws Exception { //Get factory DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); //According to the factory, get the parser DocumentBuilder builder = factory.newDocumentBuilder(); //Call parse to start parsing xml file Document document = builder.parse(new File("D:\\JAVA.Document\\xml file\\users.xml")); //Get node NodeList list = document.getElementsByTagName("Full name"); //Get label node Node node = list.item(0); //Get the text content in the label String userName = node.getTextContent(); System.out.println(userName); } //Define a method to get the value of the id attribute in the tag (query) public void read2() throws Exception { //Get factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get parser DocumentBuilder builder = factory.newDocumentBuilder(); //Parsing xml files Document document = builder.parse(new File("D:\\JAVA.Document\\xml file\\users.xml")); //Get node NodeList list = document.getElementsByTagName("Full name"); //Get label node Element node = (Element)list.item(0); String text = node.getAttribute("id"); System.out.println(text); } //change public void update() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("src/users.xml")); //Now get the parent node of the content and modify the value NodeList list = document.getElementsByTagName("Full name"); Node node = list.item(0); //This modification only modifies the objects in memory and does not write the modified data to the file node.setTextContent("Zhang San"); //Write the modified data to the file TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer former = transFactory.newTransformer(); former.transform(new DOMSource(document), new StreamResult(new File("src/users.xml"))); } //delete public void delete() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("src/users.xml")); //Get node Node node = document.getElementsByTagName("height").item(0); //Delete node: you can only get the parent node first and then delete yourself node.getParentNode().removeChild(node); //Write the modified data to the file TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer former = transFactory.newTransformer(); former.transform(new DOMSource(document), new StreamResult(new File("src/users.xml"))); } //increase public void add() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("src/users.xml")); Element node = document.createElement("user"); //Get parent node Node parentNode = document.getElementsByTagName("information").item(0); //Users mount to information parentNode.appendChild(node); Element nameNode = document.createElement("Full name"); nameNode.setTextContent("Wang Wu"); node.appendChild(nameNode); } }
3. SAX parsing
(1) The difference between SAX parsing and DOM parsing
- When using DOM to parse XML document, we need to read the whole XML document, construct the Doucment object representing the whole DOM tree in memory, and then operate on the XML document. In this case, if the XML document is very large, it will consume a lot of memory of the computer and easily lead to memory overflow.
- SAX parsing allows you to process documents when reading them, rather than wait until the entire document is loaded. Start from the top of the xml file to parse each node one by one. You can make its processing method for each node, parse it into memory one by one, and end the parsing if you find a node that meets the requirements.
(2) Advantages and disadvantages of SAX analysis
Advantages: fast processing speed, large file processing and memory saving.
Disadvantages: it can only be read, and resources will be released after line by line parsing, and its query is slow.
(3) SAX parsing steps:
① Create SAX parsing factory, parser object, XML reader
SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xmlReader = sp.getXMLReader();
② Set event handler of reader, parse xml file
xmlReader.setContentHandler(new BookParserHandler()); xmlReader.parse("xml File path");
③ Create a class for ParserHandler
And override the methods of startDocument, endDocument, startElement and endElement startDocument: start of parsing the label of xml file endDocument: start parsing the label of xml file startElement: start parsing xml file endElement: start parsing xml file characters: parsing xml node attributes You can define the global variable int index = 0 to set and parse each book in main
④ Parsing node attributes of xml files
Call the startElement(String url,String localName,String qName,Attributes attributes) method; Start parsing properties of book element if(qName.equals("book")){ //The attribute name under the book element is known, and the attribute value is obtained according to the attribute name String value = attributes.getValue("id"); //Do not know the name and number of attributes under the book element, you can use for loop to traverse the attributes under the book Attribute name: attributes.getQName(i); Attribute value: attributes.getValue(i); } Determine whether the parsing book ends Using in the endElement method if(qName.equals("book")){ End the analysis of the book }
⑤ Parsing node name and inter node text of xml file
The node name of the parsing file can be judged if(!qName.equals("book")&&!qName.equals("bookstore")){ Print out the resolution node value } New Characters method public void characters(char[] ch, int start, int length){ String value = new String(ch, start, length); if(!value.trim().equals("") {/ / remove the space after the text Value; / / node value can be obtained } }
⑥ Using xml parsing to store the content and structure of xml into Java objects
Create a new book class, create all properties, and create get and set methods When the book value is parsed, the resulting property value is set into the book method.
4. DOM4J parsing
(1) DOM4J parsing example
① DOM4J parsing node
Parsing the books.xml file (1) Create the object reader of SAXReader SAXReader reader = new SAXReader(); (2) Load the book.xml file through the read method of the reader object to obtain the document object Document document = reader.reader(new File("src/res/book.xml")); (3) Get the root node bookstores through the document object Element bookStore = document.getRootElement(); (4) Get iterator through elementinterator method exclusive to element Iterator it = bookStore.elementIterator(); (5) Traverse iterator to get information in root node (Book) while(it.hasNext()){ Element book = (Element)it.next(); Get the property name and property value of the book List<Attribute>bookAttrs = book.attribute(); Traverse all nodes in each book for (Attribute attr : bookAttrs){ Get property name attr.getName(); Get property value attr.getValue(); } }
② DOM4J parsing child node information
Traversing the book child node can still get the iterator using the elementIterator method Iterator itt = book.elementIterator(); while(itt.hasNext()){ Element bookChild = (Element)itt.next(); Get node name bookChild.getName(); Get node value bookChild.getStringValue(); }
5. JDOM parsing
(1) JDOM parsing steps
① Import jar package
② Preparations
(1)Create a SAXBuilder object SAXBuilder saxBuilder = new SAXBuilder; (2)Create an input stream that will xml File load to input stream InputStream in = new FileInputStream("src/res/books.xml"); (3)adopt saxBuilder Of build Method, load the input stream into the saxBuilder Document document = saxBuilder.build(in); (4)adopt document Object acquisition xml Root node Element rootElement = document.getRootElement(); (5)Get the List aggregate List<Element> bookList = rootElement.getChildren();
③ Resolving node properties
(1) Loop through each element in the bookList with for for(Element book : bookList){ bookList.indexof(book); you can get the current location of the book in the bookList } (2) Resolving the properties of a book List<Attribute> attrList = book.getAttributes(); Traverse attrlist (for the name and number of attributes under the unclear book node) book.getAttributeName(""); book.getAttributeValue("attribute name"); Using the above two methods, you can obtain the known node attribute name and attribute value for(Attribute attr : attrList){ Get property name String attrName = attr.getName(); Get property value String attrValue = attr.getValue(); } (3) Resolving child node names and values List<Element> bookChilds = book.getChildren(); Traverse bookchildren for (Element child : bookChilds ){ child.getName(); child.getValue(); }
④ Processing of garbled code in parsing
(1)encoding / decoding mode change (2) If (1) cannot be solved You can use inputstreamreader (, "UTF-8") instead when creating an input stream; By using character streams
⑤ Storing Book object in JDOM
(1)Establish book object Book bookEntity = new Book(); (2)judge id attribute if(attrName.equals("id")){ bookEntity.setId(attrValue) } (3)Judge attribute name if(child.getName().equals("name")){ bookEntity.setName(child.getValue()); } //Each attribute is judged by the above methods (4)Create a ArrayList To store objects private static ArrayList<book> booksList = new ArrayList<book>(); booksList.add(bookEntity); bookEntity = null;
⑥ Reference of jar package in JDOM
If you follow the previous operation, jar may be lost due to the import and export operation of the project. At this time, you can click the operation to solve the problem.
Under package, create a new folder, and then copy the jar package placed on the desktop into the new folder. Then continue to build path in package, and then select the jar package just copied.
6. Comparison of several analytical methods
(1) Classification of analytical methods
- Basic parsing methods: DOM, SAX
- Extension parsing methods: JDOM, DOM4J
(2) DOM parsing process:
- Load the entire xml file into memory at one time to form a DOM tree
- Advantages: the tree structure is formed, intuitive and easy to understand, and the code is easier to write and parse, and the tree structure is kept in memory, which is convenient to modify
- Disadvantages: when the xml file is large, the memory consumption is large, which is easy to affect the parsing performance and cause memory overflow
(3) SAX parsing process:
- Sentence by sentence judgment and parsing (time-based parsing method)
- Advantages: the event driven mode is adopted, which has a small memory consumption, and is suitable for processing only the data in xml
- Disadvantages: it is not easy to code, and it is difficult to access multiple different data in the same xml at the same time
(4) JDOM parsing process:
- Use only concrete classes instead of interfaces
- Collection classes are widely used in API
(5) DOM4J parsing process:
- An intelligent branch of JDOM that incorporates many functions beyond the basic XML document representation
- DOM4J uses interfaces and abstract basic class methods. An excellent Java XML API has the characteristics of excellent performance, good flexibility, powerful function and extremely easy to use,
- Is an open source software
4, Reflection of XML
1. Reflection introduction
- Get the object class and parse its components (methods, properties, construction methods).
- The Java reflection mechanism is to know all the properties and methods of any class in the running state, and to call any method and property of any object.
- With reflection, you can operate on Class, Constructor, Method and Field at runtime.
2. Class object
(1) getConstructor(): get the common constructor of a class
- Get nonparametric Construction: getConstructor(null);
- Get the parameter Construction: getconstructor (data type. class);
After calling the construction method, if you want to create an object with reflection, you must use the newInstance() method. If you have parameters, you need to pass them. If you have no parameters, you don't need to.
(2) getMethod(): get the public member method of a class
- Method without parameters: getMethod(null); if you want to call a method, you need to use invoke (object, null); method
- Method with parameters: getmethod (method name, data type. class); to call a method, you need to use invoke (object, parameter list); method
(3) getField(): get a public member property
Field field = clazz.getField("Member property name");
To use this property, use the field. Get (object) method to get its data. field.set() can set the data. If it is a final member property, you need to use setAccessible(true); brute force cracking
(4) getDeclaredConstructor(): get the private constructor of a class
(5) getDeclaredMethod(): get the private member method of a class
(6) getDeclaredField(): get a private member property
(4) setAccessible(true) is required for (5) and (6); brute force cracking
(7) Using reflection to create bytecode
Method 1: Class cla = Class.forName("full class name"); full class name refers to: package name. Class name
Class clazz = Class.forName("com.study.Person");//Class full name required
Method 2: Class cla = class name.class;
Class clazz = Person.class;
Method 3: Class cla = new class name(). getClass();
//Create Peron object Person p = new Person(); //Get the bytecode file object corresponding to Person through the method (getClass) inherited from object Class clazz = p.getClass();
(8) Reflection example
Example 1: reflection operation construction method
① Person class
public class Person { public String name; private int age; public Person() { System.out.println("This is a nonparametric structure"); } public Person(String name) { System.out.println(name + "This is a parametric structure"); } public Person(String name, int age) { System.out.println(name + "Say it's a parametric structure, this year" + age + "year"); } private Person(int age) { System.out.println("Private constructor" + age); } public void eat() { System.out.println("Having dinner"); } public void eat(String name) { System.out.println(name + "Having dinner"); } private void sleep() { System.out.println("Sleep"); } }
② main function class
public class Demo { @Test public void refect1() throws Exception{ //Call parameterless construction //1. Get bytecode object using reflection Class cla = Class.forName("javaeestudy.num1.Person"); //2. Use the getConstructor() method in the Class to call the public nonparametric construction method of its Class Constructor constructor = cla.getConstructor(null); constructor.newInstance(); } @Test public void refect2() throws Exception{ //Call with parameter construction //1. Get bytecode object using reflection Class cla = Class.forName("javaeestudy.num1.Person"); //2. Use the getConstructor() method in the Class to call the public parameter constructor of its Class Constructor constructor = cla.getConstructor(String.class); constructor.newInstance("Zhang San"); } @Test public void refect3() throws Exception{ //Call with parameter construction //1. Get bytecode object using reflection Class cla = Class.forName("javaeestudy.num1.Person"); //2. Use the getConstructor() method in the Class to call the public parameter constructor of its Class Constructor constructor = cla.getConstructor(String.class, int.class); constructor.newInstance("Zhang San", 18); } @Test public void refect4() throws Exception{ //Call private constructor //1. Get bytecode object using reflection Class cla = Class.forName("javaeestudy.num1.Person"); //2. Use the getConstructor() method in the Class to call the private constructor of its Class Constructor constructor = cla.getDeclaredConstructor(int.class); //3. Open brute force constructor.setAccessible(true); constructor.newInstance(18); } }
Example 2: reflecting operations on methods and properties
public class Demo2 { @Test public void method1() throws Exception { //Using reflection to manipulate methods in its classes Class cla = Class.forName("javaeestudy.num1.Person"); //Parameter (name, parameter), name means method name, parameter means data type of parameter Method method = cla.getMethod("eat", null); //invoke(obj, args) method, use object call method, obj represents object, args represents parameter value method.invoke(cla.newInstance(), null); } @Test public void method2() throws Exception { //Operation with parameters Class cla = Class.forName("javaeestudy.num1.Person"); //Parameter (name, parameter), name means method name, parameter means data type of parameter Method method = cla.getMethod("eat", String.class); //invoke(obj, args) method, use object call method, obj represents object, args represents parameter value method.invoke(cla.newInstance(), "Zhang San"); } @Test public void method3() throws Exception { //Operation private method Class cla = Class.forName("javaeestudy.num1.Person"); //Parameter (name, parameter), name means method name, parameter means data type of parameter Method method = cla.getDeclaredMethod("sleep", String.class); //Open violent dismantling method.setAccessible(true); //invoke(obj, args) method, use object call method, obj represents object, args represents parameter value method.invoke(cla.newInstance(), "Zhang San"); } @Test public void method4() throws Exception { //Operation common properties Class cla = Class.forName("javaeestudy.num1.Person"); Field field = cla.getField("name"); //Get the value of the field //obj parameter, which represents the field of that object String obj = (String) field.get(cla.newInstance()); System.out.println(obj); } @Test public void method5() throws Exception { //Operation common properties Class cla = Class.forName("javaeestudy.num1.Person"); Field field = cla.getDeclaredField("age"); //Open violent dismantling field.setAccessible(true); //Get the value of the field //obj parameter, which represents the field of that object int age = field.getInt(cla.newInstance()); System.out.println(age); } }
Example 3: by manipulating xml files and anti manipulation methods
① xml file
<?xml version="1.0" encoding="utf-8" standalone="yes" ?> <package pname="javaeestudy.study"> <clazz cname="Person"> <method type="public">eat</method> <method type="private">sleep</method> </clazz> </package>
② Person class
public class Person { //Public method public void eat() { System.out.println("Having dinner"); } //Private method private void sleep() { System.out.println("Sleep"); } }
③ main function: operation class
public class Demo { public static void main(String[] args) throws Exception { new Demo2().method1(); } //Operation method public void method1() throws Exception { Document document = getDocument(); //Get package name NodeList packageList = document.getElementsByTagName("package"); Element packageNode = (Element)packageList.item(0); String text = packageNode.getAttribute("pname"); //Get class name NodeList clazzList = document.getElementsByTagName("clazz"); Element clazzNode = (Element)clazzList.item(0); text = text + "." + clazzNode.getAttribute("cname"); //Get bytecode object using reflection Class cla = Class.forName(text); //Get method node NodeList methodList = document.getElementsByTagName("method"); for(int i = 0; i < methodList.getLength(); i++) { //Get method type Element typeNode = (Element)methodList.item(i); String typeText = typeNode.getAttribute("pname"); //Get method name Node methodNode = methodList.item(i); String methodName = methodNode.getTextContent(); Method method = null; if(typeText.equals("public")) { //Use the getMethod method method in the Class to call the public nonparametric constructor of its Class method = cla.getMethod(methodName, null); }else { //Use the getDeclaredMethod method in the Class to call the private parameterless construction method of its Class method = cla.getDeclaredMethod(methodName, null); //Open violent dismantling method.setAccessible(true); } //invoke(obj, args) method, use object call method, obj represents object, args represents parameter value method.invoke(cla.newInstance(), null); } } //Get document method public Document getDocument() throws Exception { //Get factory DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); //According to the factory, get the parser DocumentBuilder builder = factory.newDocumentBuilder(); //Call parse to start parsing xml file return builder.parse(new File("src\\javaeestudy\\study\\person.xml")); } }