An overview of XML
-
What is the XML
- XML refers to extensible Markup Language (EXtensible Markup LAnguage)
- XML is a markup language, much like HTML
- XML is designed to transmit data, not display it
- XML tags are not predefined. You need to define your own tags.
- XML is designed to be self-descriptive.
-
Differences between XML and HTML
XML is designed to transport and store data, with the focus on the content of the data.
HTML is designed to display data, and the focus is on what the data looks like.
HTML is designed to display information, while XML is designed to transmit information.
-
XML syntax rules
-
XML document declaration
For XML documents, you must write a document declaration, which is written in a fixed format and can only appear at row 0 column 0
Copy the code
-
XML document composition:
Tag: Element Tag Attribute of the Element tag: Attribute Attribute value of the tag: attributeValue Tag body text: textCopy the code
-
XML syntax rules
- Strictly case sensitive - attribute values must have quotes - Documents must have root elements - All XML elements must have closing tagsCopy the code
-
Configuration file
Both XML and Properties files are configuration files, which are specially formatted files used to provide configuration parameters and initialization Settings to an application
-
Properties file configuration (instance druid.properties)
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bookstore? rewriteBatchedStatements=true
username=root
password=888888
Copy the code
-
XML file configuration
<! XML database configuration -->
<config>
<! -- Configure database driver -->
<jdbc name="driver" value="com.mysql.jdbc.driver"/>
<jdbc name="url" value="jdbc:mysql://localhost:3306/test? characterEncoding=utf8"/>
<jdbc name="user" value="root"/>
<jdbc name="password" value="root"/>
</config>
Copy the code
By comparison, you can see that XML must write the document declaration at row 0 column 0, and the tag and attribute names can be customized.
-
XML constraints
-
DTD
A Document Type Definition (DTD) is a Document Type Definition used to constrain XML documents. Specify the names of the elements in the XML document, the names and order of the child elements, the attributes of the elements, and so on. How to create AN XML document: add the suffix.xml to the file name when creating file. DTD file
<? The XML version = "1.0" encoding = "utf-8"? > <! ELEMENT beans (bean*,import*) > <! --* indicates zero or more times, and comma (,) indicates order --> <! ELEMENT bean (property*)> <! ELEMENT property (#PCDATA)> <! ELEMENT import (#PCDATA)> <! -- Bean must have id,className--> <! ATTLIST bean id CDATA #REQUIRED className CDATA #REQUIRED > <! -- Property must have name,value--> <! ATTLIST property name CDATA #REQUIRED value CDATA #REQUIRED > <! --import must contain resource--> <! ATTLIST import resource CDATA #REQUIRED>Copy the code
If developers want to use current DTD constraints on XML, they must include a DOCTYPE. DOCTYPE beans SYSTEM “bean.dtd”>
<! Write your own XML configuration based on existing DTD constraints.
<! Introduce an external DTD file to control our own XML authoring.
<! DOCTYPEbeans SYSTEM "beans.dtd">
<beans>
<bean id="a" className="className">
<property name="zhangsan" value="123">Write random text</property>
</bean>
<import resource="resource">
</import>
</beans>
Copy the code
-
Schema
The document extension is XSD, and the Schema emulates the Spring specification. If a developer wants to use the current Schema constraint in XML, he must include the specified namespace (namespace, or XMLNS, which is equivalent to an import package in Java). The format is as follows:
Beans XMLNS = “www.atguigu.com/bean” XMLNS: xsi = “www.w3.org/2001/XMLSch…” xsi:schemaLocation=”www.atguigu.cn/bean bean-schema.xsd”
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.atguigu.cn/bean"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://www.atguigu.cn/bean"
elementFormDefault="qualified">
<! Declare the root tag -->
<element name="beans">
<complexType>
<choice minOccurs="0" maxOccurs="unbounded">
<element name="bean">
<complexType>
<sequence minOccurs="0" maxOccurs="unbounded">
<element name="property">
<complexType>
<attribute name="name" use="required"></attribute>
<attribute name="value" use="required"></attribute>
</complexType>
</element>
</sequence>
<attribute name="id" use="required"></attribute>
<attribute name="className" use="required"></attribute>
</complexType>
</element>
<element name="import">
<complexType>
<attribute name="resource" use="required"></attribute>
</complexType>
</element>
</choice>
</complexType>
</element>
</schema>
Copy the code
Using existing SXD files, write our own XML
<qq:beans xmlns:qq="http://www.atguigu.cn/bean"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.atguigu.cn/bean beans.xsd"
>
<qq:bean id="a"
className="sss">
<qq:property name="sss" value="www"/>
</qq:bean>
<qq:import resource="sss"/>
<qq:import resource="ddd"/>
</qq:beans>
Copy the code
-
XMLNS = "http://www.atguigu.cn/bean" the name of the XML namespaces W3C standards: namespace name, must be the global uniquenessCopy the code
-
XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" official W3C constraintsCopy the code
-
Xsi: schemaLocation = "http://www.atguigu.cn/bean beans. XSD" is defined, the constraint of the namespace, and constraints of the file pathCopy the code
4. XML parsing (emphasis)
-
The role of XML parsing
Read data in XML with Java code
-
Analytical way
- Dom parsing: The document is loaded into memory to form a DOM tree (Document object) that encapsulates the various parts of the document as objects. Dom trees are memory intensive and slow to parse. Therefore, DOM parsing is generally not used when parsing large XML files
- SAX parsing: Reads line by line, event-driven, parses line by line and releases line by line, very small memory footprint. This is not used when parsing large XML files
-
The parser
- JAXP: Parsing provided by Sun. Support for DOM and SAX. (not often used)
- JDOM
- DOM4J (common)
Use DOM4J
- Create the XML file, student.xml, under SRC
<students>
<student name="Zhang" age="20">
<score name="Mathematics">100</score>
<score name="Chinese">30</score>
</student>
<student name="Bill" age="21">
<score name="Mathematics">15</score>
<score name="Chinese">99</score>
</student>
</students>
Copy the code
- Create a lib package with dom4j.jar(core class is SaxReader)
- Create the ReadXml class to read the XML
package com.atguigu.read;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.List;
public class ReadXml {
public static void main(String[] args) throws Exception {
// Byte input stream, binding XML file
InputStream input
=ReadXml.class.getClassLoader().getResourceAsStream("student.xml");
// Create a core class object
SAXReader saxReader = new SAXReader();
// the saxReader method read passes the input stream, reads the XML file, and returns the Document object Document
Document document = saxReader.read(input);
// Read the document root tag: students
Element rootElement = document.getRootElement();
// Read the child tag of the root tag
List
elements() returns a List collection
List<Element> studentElements = rootElement.elements();
for(Element studentElement : studentElements){
//studentElement object, each student tag object
//studentElement object method attributeValue gets the attributeValue and returns a string
String name = studentElement.attributeValue("name");
String age = studentElement.attributeValue("age");
System.out.println(name+"... ""+age);
// Get the score tag of student tag
List<Element> scoreElements = studentElement.elements();
for(Element scoreElement : scoreElements){
//scoreElement gets the subtag score
// Score tag attribute value
String scoreName = scoreElement.attributeValue("name");
GetText (); // Score tag body gets, is plain text string scoreElement method getText()
String text = scoreElement.getText();
System.out.println("\t"+scoreName+"... ""+text); }}}}Copy the code
- Gets all child labels
List<Element> sonElementList = rootElement.elements();
- Gets the child label of the specified label name
List<Element> sonElementList = rootElement.
- Gets the value of a tag attribute
String value = element.AttributeValue(" attribute name ");
XPATH USES
Use XPATH tools for direct positioning, which is fast and requires less code, and guide the JAXEN-1.1-beta-6.jar package
package com.atguigu.read;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.List;
public class XpathXml {
public static void main(String[] args) throws Exception{
// Byte input stream, binding XML file
InputStream input =
ReadXml.class.getClassLoader().getResourceAsStream("student.xml");
// Create a core object
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(input);
Element rootElement = document.getRootElement();
// Read the tag score directly
// The tag object method List<> selectNodes("// tag name "), which returns a collection of values List
List scoreElements = rootElement.selectNodes("//score");
for(Object object : scoreElements){
//Object Forcibly converts to label Object
Element scoreElement = (Element)object;
System.out.println(scoreElement.attributeValue("name") +"... ""+ scoreElement.getText());
}
System.out.println("= = = = = = = = = = = = = =");
// The selectSingleNode method gets a label and returns the value Node interface object
// Tag object Element interface, inherit Node interface
Element node = (Element) rootElement.selectSingleNode("//score");
System.out.println(node.attributeValue("name") +"... ""+node.getText()); }}Copy the code
SelectSingleNode (” path rule “): searches for the first node that meets the condition based on the path rule. SelectNodes (” path rule “): searches for all nodes that meet the condition based on the path rule