Java Learning Route (26) - XML and Design Patterns

1. XML

(1) The concept of XML: XML is Extensible Markup Language (Extensible Markup Language), a data representation form that can describe very complex data structures, and is often used to transmit and store data.

(2) Features of XML

  • XML data is in plain text form, UTF-8 encoding is used by default
  • nestable

(3) XML usage scenarios: XML content is often used as a message for network transmission, or used as a configuration file to store system information.

(4) XML syntax

1. File format: [xxx_xxx.xml]
2. Document statement (must be on the first line):

<?xml version="1.0" encoding="UTF-8" ?>

3. Labeling rules

  • A tag is composed of a pair of closing tags (such as <src></src>), of which there is only one root tag.
  • Special tags such as single closing tags must have an end tag (such as <br/>)
  • Tags can define attributes, attributes and tag names are separated by spaces, and attribute values ​​must be assigned with quotation marks. (such as <student id="1"></student>)
  • Note: Use the format of [<!-- xxxx -->]
  • Angle brackets in the body may conflict with tags, so special characters need to be used instead of angle brackets, special character format: [&xxxx;]
Special characters replaced character
&lt <
&gt >
&amp &
&apos
&quot "
  • XML data area CDATA: [<![CDATA[ … ]]]

(1) XML example

<?xml version="1.0" encoding="UTF-8" ?>
<!--根标签只有一个-->
<student>
    <name>病态王子</name>
    <sex></sex>
    <hobby>傲娇</hobby>
    <info>
        <age>25</age>
        <addr>中国</addr>
    </info>
    <!-- 尖括号可能会发生冲突,所以需要用特殊字符代替尖括号 -->
    <sql>
        select id from user where age &gt; 20;
        <![CDATA[
            select * from user where age < 18;
        ]]>
    </sql>
</student>

(2) XML browser parsing results

<!-- 根标签只有一个 -->
<student>
<name>病态王子</name>
<sex>男</sex>
<hobby>傲娇</hobby>
<info>
<age>25</age>
<addr>中国</addr>
</info>
<!--  尖括号可能会发生冲突,所以需要用特殊字符代替尖括号  -->
<sql>
select id from user where age > 20;
<![CDATA[ select * from user where age < 18; ]]>
</sql>
</student>

(5) Document constraints

**1. Concept: **Document constraints are used to limit the writing of tags and attributes in xml files.

2. Classification:
(1) DTD

DTD constraint document xxx.dtd

<!ELEMENT 暑假(书+)>
<!ELEMENT 书(书名,作者,售价)>
<!ELEMENT 书名(#PCDATA)>
<!ELEMENT 作者(#PCDATA)>
<!ELEMENT 售价(#PCDATA)>

Write xml import DTD document

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE 书架 SYSTEM "xxx.dtd"

Advantages and disadvantages of DTD constraints

  • Advantages: Can constrain the writing of XML files
  • Disadvantage: cannot constrain specific data types

(2)schema

Concept: schema is a strongly constrained XML, which is also required by other constrained files

Steps for usage

  • 1. Write a schema constraint document named [xxx.xsd]
  • 2. XML import schema constraint document

text.xsd

<?xml version="1.0" encoding="UTF-8" ?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.itcast.cn"
        elementFormDefault="qualified" >
<!--targetNamespace:声明约束文档的地址(命名空间) -->
    <element name="书架">
<!--        子元素-->
        <complexType>
            <sequence maxOccurs="unbounded">
                <element name="">
                    <complexType>
                        <sequence>
                            <element name="书名" type="string"/>
                            <element name="作者" type="string"/>
                            <element name="售价" type="double"/>
                        </sequence>
                    </complexType>
                </element>
            </sequence>
        </complexType>
    </element>
</schema>

XML introduces schema constraints

<?xml version="1.0" encoding="UTF-8" ?>
<!--导包itcast 与 schema对象 -> 引入约束文件 -->
<书架 xmlns="http://www.itcast.cn"  
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.itcast.cn text.xsd">
    <>
        <书名>《红楼梦》</书名>
        <作者>曹雪芹</作者>
        <售价>20.0</售价>
    </>
</书架>

Two, XML parsing

(1) Concept: XML parsing is to use programs to read data in XML.

(2) Analysis method:
1. SAX analysis
2. DOM analysis

(1) DOM parsing document object process

  • Read the document into the memory, the root node is the Document object
  • The XML root node is a layer 2 node
  • The element label is the Element object of the third-level node
  • The attribute label is the Attribute object of the 4th layer node
  • The text content is the Text object of the fifth layer node

insert image description here

(3) Common analysis tools

tool illustrate
JAXP A set of XML parsing API provided by SUN
JDOM Based on the tree structure, JDOM uses pure JAVA technology to parse, generate, serialize and perform other operations on XML documents
dom4j JDOM puls, used to read and write XML files. It has the characteristics of good performance, strong function and easy to use.
are p Powerful DOM-style XML parsing development kit, more convenient for HTML parsing

(4) Use Dom4j to parse XML

1. Use process

  • Download the jar package: dom4j-2.1.1.jar
  • import jar package
  • use jar package

2. Dom4j analysis
(1) Get the Document object

constructor/method illustrate
SAXReader() Create a Dom4j parser
Document read(String url) Load XML into a Document object

(2) Get the root element object

method illustrate
Element getRootElement() Get the root element object

(3) Element element object API

method illustrate
List<Element> elements() Get all child elements under the current element
List<Element> elements(String name) Get all child elements with the specified name under the current element
Element element(String name) Get the first child element with the specified name under the current element
String getName() get element name
String attributeValue(String name) Get attribute value based on attribute name
String elementText (child element name) Get the text of the child element with the specified name
String elementTextTrim (child element name) Get the subelement text of the specified name and remove leading and trailing spaces
String getText() get text
String attributeValue (attribute name) get attribute value
    @Test
    public void parseData() throws DocumentException {
    
    
        //1、创建解析器
        SAXReader reader = new SAXReader();

        //2、XML加载
//        Document document = reader.read("D:\\JavaBase\\JavaSEpro\\src\\text.xml");
        //默认在src寻找对应文件名称的文件进行加载
        Document document = reader.read(Dom4JParseDemo.class.getResourceAsStream("/text.xml"));

        //3、获取根元素
        Element root = document.getRootElement();
        System.out.println("根元素:"+root.getName());

        //4、子元素(一级)
        List<Element> elements = root.elements();
        System.out.println("===============一级子元素==============");
        for (Element e :elements) {
    
    
            System.out.println(e.getName());
        }

        //5、获取指定元素以及元素值
        System.out.println("===============指定子元素==============");
        System.out.println(root.elementText("name"));
        System.out.println(root.elementTextTrim("hobby"));

        //6、根据元素获取属性值
        Attribute idAttr = root.attribute("id");
        System.out.println(idAttr.getName() + " = " +idAttr.getValue());
    }

/*打印输出*/
根元素:student
===============一级子元素==============
name
sex
hobby
info
sql
===============指定子元素==============
病态王子
傲娇
id = 1

3. File analysis case

(1) Requirement: According to the given XML file, output the file data according to the specified style
(2) Implementation:

Material data.xml

<?xml version="1.0" encoding="UTF-8" ?>
<contactList>
    <contact id="1">
        <name>潘金莲</name>
        <gender></gender>
        <email>[email protected]</email>
    </contact>
    <contact id="2">
        <name>武松</name>
        <gender></gender>
        <email>[email protected]</email>
    </contact>
    <contact id="3">
        <name>武大郎</name>
        <gender></gender>
        <email>[email protected]</email>
    </contact>
</contactList>

Implementation code

    @Test
    public void parseDemo() throws DocumentException {
    
    
        SAXReader reader = new SAXReader();

        Document document = reader.read(Dom4JParseDemo.class.getResourceAsStream("/data.xml"));

        Element root = document.getRootElement();
        String rootName = root.getName();

        List<Element> memberNode = root.elements();
        for (Element e :memberNode) {
    
    
            System.out.println(e.getName() + "{id=" + e.attribute("id").getValue() + ", name=" + e.elementTextTrim("gender") + ", email=" + e.elementTextTrim("email") + "}");
        }
    }

printout

contact{id=1, name=女, [email protected]}
contact{id=2, name=男, [email protected]}
contact{id=3, name=男, [email protected]}

2. XML file retrieval

(1) Tools: XPath

(2) Use of XPath
1. Import jar packages: dom4j and jaxen
2. Obtain Document through dom4j
3. Use XPath to complete the parsing operation

(3) Related APIs

method illustrate
Node selectSingleNode("expression") Get the only elements matching the expression
List<Node> selectNodes("expression") get all elements matching the expression

(4) Three search methods

1. Absolute path search

public class XPathDemo {
    
    
    @Test
    public void parse1() throws DocumentException {
    
    
        //1、解析器
        SAXReader reader = new SAXReader();
        //2、Document对象
        Document document = reader.read(XPathDemo.class.getResourceAsStream("/data.xml"));
        //3、XPath路径搜索

        //绝对路径搜索
        List<Node> nodes = document.selectNodes("/contactList/contact/name");
        
        for (Node node:nodes) {
    
    
            Element element = (Element) node;
            System.out.println(element.getTextTrim());
        }
    }
}

/*打印输出*/
潘金莲
武松
武大郎

2. Relative path search

public class XPathDemo {
    
    
    @Test
    public void parse1() throws DocumentException {
    
    
        //1、解析器
        SAXReader reader = new SAXReader();
        //2、Document对象
        Document document = reader.read(XPathDemo.class.getResourceAsStream("/data.xml"));
        //3、XPath路径搜索

        //相对路径搜索
		List<Node> nodes = document.getRootElement().selectNodes("./contact/name");

        for (Node node:nodes) {
    
    
            Element element = (Element) node;
            System.out.println(element.getTextTrim());
        }
    }
}

/*打印输出*/
潘金莲
武松
武大郎

3. Full text search

public class XPathDemo {
    
    
    @Test
    public void parse1() throws DocumentException {
    
    
        //1、解析器
        SAXReader reader = new SAXReader();
        //2、Document对象
        Document document = reader.read(XPathDemo.class.getResourceAsStream("/data.xml"));
	    //3、Xpath全文检索(只要符合该路径就会匹配)
	    //注意:// --> 代表全文搜索, / --> 代表当前路径,两者可以混合使用
	    //例如 //contect/name 代表全文搜索所有contect的一级元素为name的属性值。
		List<Node> nodes =  document.selectNodes("//name");

        for (Node node:nodes) {
    
    
            Element element = (Element) node;
            System.out.println(element.getTextTrim());
        }
    }
}

/*打印输出*/
潘金莲
武松
武大郎

4. Attribute search

public class XPathDemo {
    
    
    @Test
    public void parse1() throws DocumentException {
    
    
        //1、解析器
        SAXReader reader = new SAXReader();
        //2、Document对象
        Document document = reader.read(XPathDemo.class.getResourceAsStream("/data.xml"));
        //3、XPath路径搜索

        System.out.println("===========方式1===========");
        //所有id属性
        List<Node> nodes = document.selectNodes("//@id");
        for (Node node:nodes) {
    
    
            Attribute element = (Attribute) node;
            System.out.println(element.getValue());
        }

        System.out.println("===========方式2===========");
        //name标签中中包含id属性的元素
        List<Node> nodes1 = document.selectNodes("//contact[@id]");
        for (Node node:nodes1) {
    
    
            Element element = (Element) node;
            System.out.println(element.getName());
        }

        System.out.println("===========方式3===========");
        //name标签中中包含id属性值为1的元素
        List<Node> nodes2 = document.selectNodes("//contact[@id=1]");
        for (Node node:nodes2) {
    
    
            Element element = (Element) node;
            System.out.println(element.getName());
        }
    }
}

/*打印输出*/
===========方式1===========
1
2
3
===========方式2===========
contact
contact
contact
===========方式3===========
contact

3. Design pattern
(1) Factory pattern

1. Concept: a mode of creating objects internally and providing a method of obtaining objects externally.

2. Function:

  • Factory methods can encapsulate details of object creation, such as object initialization
  • It is possible to realize the decoupling operation between classes (core idea) - that is, not to let the classes be directly associated.

3. Achieve:

public class FactoryDemo {
    
    
    public static void main(String[] args) {
    
    
        Computer c1 = FactoryPattern.getComputer("mac");
        Computer c2 = FactoryPattern.getComputer("huawei");
        c1.run();
        c2.run();
    }
}

class Computer{
    
    
    protected String name;
    protected double price;

    public Computer(){
    
    }

    public Computer(String name, double price) {
    
    
        this.name = name;
        this.price = price;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public double getPrice() {
    
    
        return price;
    }

    public void setPrice(double price) {
    
    
        this.price = price;
    }

    public void run(){
    
    
        System.out.println(this.name + "正在启动。。。");
    };

    @Override
    public String toString() {
    
    
        return "Computer{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

class Mac extends Computer{
    
    

    public Mac() {
    
    
    }

    public Mac(String mac, double price) {
    
    
        this.name = mac;
        this.price = price;
    }
}

class HuaWei extends Computer{
    
    
    public HuaWei() {
    
    
    }

    public HuaWei(String name, double price) {
    
    
        super(name, price);
    }
}

class FactoryPattern{
    
    
    public static Computer getComputer(String info){
    
    
        switch (info){
    
    
            case "mac":
                return new Mac("Mac",9999);
            case "huawei":
                return new HuaWei("HuaWei",5999);
            default:
                return null;
        }
    }
}

/*打印输出*/
Mac正在启动。。。
HuaWei正在启动。。。

(2) Decoration mode

1. Concept: Create a new class, wrap the original class, and enhance the function of the original class.

2. Function:

  • A method to dynamically extend a class without changing the original class. - is actually a utility class with a primitive class.
  • It is possible to realize the decoupling operation between classes (core idea) - that is, not to let the classes be directly associated.

3. Achieve:

public class DecaratorDemo {
    
    
    public static void main(String[] args) {
    
    
        InputStream inputStream = new FileInputStream();
        System.out.println(inputStream.read());
        byte[] bytes = new byte[100];
        System.out.println(inputStream.read(bytes));
        System.out.println(Arrays.toString(bytes));
    }
}

abstract class InputStream{
    
    
    public abstract int read();
    public abstract int read(byte[] buffer);
}

class FileInputStream extends InputStream{
    
    

    @Override
    public int read() {
    
    
        System.out.println("读取了一个字节a");
        return 97;
    }

    @Override
    public int read(byte[] buffer) {
    
    
        for (int i = 0; i < 26; i++) {
    
    
            buffer[i] = (byte) (97 + i);
        }
        System.out.println("读取了一个字节数组");
        return 26;
    }
}

/*打印输出*/
读取了一个字节a
97
读取了一个字节数组
26
[97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Guess you like

Origin blog.csdn.net/Zain_horse/article/details/131098790