JavaWeb--XML (the only way of data processing)

Posted by chiefmonkey on Mon, 20 Dec 2021 21:06:36 +0100

JavaWeb – XML (the only way to process data)

Read the whole XML in one article
This paper systematically and comprehensively introduces XML, and realizes the understanding, understanding and application of the whole XML in this paper. It will lead you to better study XML

The role of XML

What is XML

Extensible markup language, a subset of the standard general markup language, referred to as XML. Is a kind of markup language used to mark electronic documents to make them have structure.
xml (Extensible Markup Language). The suffix of the file is:. xml. Just as HTML is used to display data, xml is used to transmit and store data.

Comparison between XML and HTML

Purpose of XML

In order to facilitate data sharing and communication between different applications and platforms.

  • It can be used as a simple database to store and retrieve data;

  • Transmission of documents in the agreed format;

  • Make the configuration file of the software. [configuration file: file for saving software settings]

XML writing syntax rules

  • XML document structure
  • XML declaration

XML tag writing rules

  • Legal tag name

  • Appropriate comments and indents

  • Rational use attribute

  • Handling special characters

  • xml file exercise

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hr SYSTEM "hr.dtd">
<hr>
    <employee no="3309">
        <name>Zhang San</name>
        <age>18</age>
        <salary>3000</salary>
        <department>
            <dname>Accounting department</dname>
            <address>Chongqing xx large building-A1</address>
        </department>
    </employee>
    <employee no="3310">
        <name>Li Si</name>
        <age>22</age>
        <salary>4000</salary>
        <department>
            <dname>engineering department</dname>
            <address>Chongqing xx large building-B4</address>
        </department>
    </employee>
</hr>

Drag the file into the browser (the browser used by the author is Google) to display the file.

CDATA Tags

  • Ordered child elements

Parsing XML with Java

Dom4j

Download address: https://dom4j.github.io/
Note: the version of Dom4j has restrictions on the version of jdk. You should pay attention to version control when downloading.

Use to read xml files

package JavaWeb.xml.dom4j;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

public class HrReader {
    public void readXml(){
        String file = "F:/xxx/src/JavaWeb/xml/hr.xml";
        //SAXReader class is the core class for reading XML files. It is used to save XML parsed in memory in the form of "tree"
        SAXReader reader = new SAXReader();
        try {
            Document document=reader.read(file);
            //Gets the root node of the XML document, the hr tag
            Element root = document.getRootElement();
            //The elements method is used to obtain the specified set of tags
            List<Element> employees =root.elements("employee");
            for (Element employee : employees){
                //The element method is used to obtain a unique child node object
                Element name = employee.element("name");
                String empName = name.getText();//The getText() method is used to get the label text
                System.out.println(empName);
                System.out.println(employee.elementText("age"));
                System.out.println(employee.elementText("salary"));
                Element department = employee.element("department");
                System.out.println(department.element("dname").getText());
                System.out.println(department.element("address").getText());
                Attribute att = employee.attribute("no");
                System.out.println(att.getText());
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HrReader reader = new HrReader();
        reader.readXml();
    }
}

Use to write xml files

package JavaWeb.xml.dom4j;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXWriter;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class HrWriter {
    public void writerXml(){
        String file = "F:/xxx/src/JavaWeb/xml/hr.xml";
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(file);
            Element root = document.getRootElement();
            Element employee=root.addElement("employee");
            employee.addAttribute("no","3311");
            Element name =employee.addElement("name");
            name.setText("Li Tiezhu");
            employee.addElement("age").setText("19");
            employee.addElement("salary").setText("3600");
            Element department = employee.addElement("department");
            department.addElement("dname").setText("Ministry of Personnel");
            department.addElement("address").setText("Chongqing xx large building-c4");
            Writer writer = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
            document.write(writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HrWriter hrWriter = new HrWriter();
        hrWriter.writerXml();
    }
}


After writing, return to view the xml file (hr,xml in this case). The file will add the content written by HrWriter

Statement constraints for XML

XML statement constraints

DTD




  • DTD file exercise
<?xml version="1.0" encoding="UTF-8" ?> 
<!ELEMENT hr (employee+)>
<!ELEMENT employee (name,age,salary,department)>
<!ATTLIST employee no CDATA "">
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT salary (#PCDATA)>
<!ELEMENT department (dname,address)>
<!ELEMENT dname (#PCDATA)>
<!ELEMENT address (#PCDATA)>

XML Schema

Why XSD is a substitute for DTD

  • Expandable according to future conditions
  • Richer and more useful than DTD
  • Write in XML
  • Supported data types
  • Namespace is not supported.
    Advantages of XML Schema:
  1. XML Schema is based on XML and has no special syntax
  2. XML Schema can be parsed and processed like other XML files
  3. XML Schema provides richer data types than DTD
  4. XML Schema provides an extensible data model.
  5. XML Schema supports comprehensive namespaces
  6. XML Schema supports attribute groups.
  • xml schema exercise
<?xml version="1.0" encoding="UTF-8" ?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
    <element name="hr">
        <complexType>
            <sequence>
                <element name="employee" minOccurs="1" maxOccurs="unbounded">
                    <complexType>
                        <sequence>
                            <element name="name" type="string"></element>
                            <element name="age">
                                <simpleType>
                                    <restriction base="integer">
                                        <minInclusive value="18"></minInclusive>
                                        <maxInclusive value="60"></maxInclusive>
                                    </restriction>
                                </simpleType>
                            </element>
                            <element name="salary" type="integer"></element>
                            <element name="department">
                                <complexType>
                                    <sequence>
                                        <element name="dname" type="string"></element>
                                        <element name="address" type="string"></element>
                                    </sequence>
                                </complexType>
                            </element>
                        </sequence>
                        <attribute name="no" type="string" use="required"></attribute>
                    </complexType>
                </element>
            </sequence>
        </complexType>
    </element>
</schema>

Path expression for Xpath




Jaxen

Download address: http://www.java2s.com/Code/Jar/j/Downloadjaxen112jar.htm

package JavaWeb.xml.Xpath;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.util.List;

public class XpathTest {
    public void xpath(String xpathExp){
        String file = "F:/xxx/src/JavaWeb/xml/hr.xml"; //Query file location
        SAXReader reader = new SAXReader(); //SAXReader class is the core class for reading XML files. It is used to save XML parsed in memory in the form of "tree".
        try {
            Document document = reader.read(file);
            List<Node> nodes = document.selectNodes(xpathExp);
            for(Node node : nodes){
                Element emp =(Element)node;
                System.out.println(emp.attributeValue("no"));
                System.out.println(emp.elementText("name"));
                System.out.println(emp.elementText("age"));
                System.out.println(emp.elementText("salary"));
                System.out.println("=========================");
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        XpathTest test = new XpathTest();
//        test.xpath("/hr/employee"); // Query employee under HR node
//        test.xpath("//employee");     // Query the employee of any node
//          test. xpath("//employee[salary<3600]");// Query employees whose salary is less than 3600
//        test.xpath("//employee[name = 'Li Tiezhu'])// Query the employee whose name is Li Tiezhu
//            test.xpath("//employee[@no=3309]");// Query the employee whose condition no is 3309
//        test.xpath("//employee[1]");// Query the first employee
//        test.xpath("//employee[last()]");// Query the last employee
//        test. xpath("//emp loyee[position()<3]");// Query the first three EMPs
        test.xpath("//employee[3] | //employee[2] "); / / query the third and second employees
    }

}

Topics: Java xml xpath java web