2021-07-29 Java, XML and JSON

XML

brief introduction

Extensible markup language

characteristic:

  1. xml is a platform independent markup language
  2. xml is self descriptive

Purpose:

  1. Network data transmission
  2. Data storage
  3. Profile (key)

XML file:
. XML file is a way to save XML data, and XML data can also exist in other forms (such as building XML data in memory). Do not narrowly understand XML language as XML file

XML syntax

1.XML document declaration

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

2. Tag (element / tag / node)

An XML document consists of tags.
Syntax:

  • Start tag (open tag): < tag name >
  • End tag (closed tag): < / tag name >

Tag name: a custom name that must follow the following naming rules:

  1. The name can contain characters, numbers, and other characters
  2. The name cannot start with a number or punctuation mark
  3. The name cannot start with the character "xml" (or xml, xml)
  4. The name cannot contain spaces or colons (:)
  5. Names are case sensitive

Tag content: the tag content is between the start tag and the end tag.
For example, we use tags to describe a person's name:

<name>Wu Yanzu</name>

3. In an XML document, there must be and only one root tag is allowed.

Positive example:

<name>
	<name>Zhang San</name>
	<name>Li Si</name>
</name>

Counterexample:

<name>Zhang San</name>
<name>Li Si</name>

4. Tags can be nested, but cross is not allowed

Positive example:

<person>
   <name>Li Si</name>
   <age>18</age>
</person>

Counterexample:

<person>
	<name>Li Si<age></name>
	18</age>
</person>

5. Hierarchical address of markers (child marker, parent marker, brother marker, descendant marker, ancestor marker)

For example:

<persons>
	<person>
		<name>Li Si</name>
		<age>180cm</age>
	<person>
	<person>
		<name>Li Si</name>
		<length>200cm</length>
	</person>
</persons>

name is a child marker of person and a descendant marker of person.
name is the descendant tag of persons.
name is the sibling token of length.
person is the parent tag of name.
People is the ancestor token of name.

6. Duplicate tag names are allowed

7. In addition to the start and end, the tag also has attributes.

The attribute in the tag is described at the beginning of the tag and consists of attribute name and attribute value
Format;

  • In the start tag, describe the attribute
  • It can contain 0-n attributes, and each attribute is a key value pair!
  • Duplicate attribute names are not allowed. Equal signs are used between keys and values. Multiple attributes are separated by spaces. Attribute values must be enclosed in quotation marks.

Case:

<persons>
	<person id="1001" groupid="1">	
		<name>Li Si</name>
		<age>18</age>
	</person>
	<person id="1002" groupid="2">	
		<name>Li Si</name>
		<age>20</age>
	</person>
</persons>

8. Notes

Comments cannot be written before the document declaration
Comments cannot be nested
Format:

  • Comment start: <! –
  • End of note: – >

Java parsing XML (Master)

Interview questions

Q: how many XML parsing methods are there in Java? What are they? What are the advantages?
Answer:
1.SAX analysis
The parsing method is event driven mechanism
SAX parser reads XML file parsing line by line, and triggers an event whenever it parses to the start / end / content / attribute of a tag.
We can write programs to deal with these events when they occur.
advantage:

  • Analysis can start immediately instead of waiting for all data to be processed
  • Load line by line to save memory and help parse documents larger than system memory
  • Sometimes you don't have to parse the whole document. It can stop parsing when a certain condition is met.
    Disadvantages:
  • For one-way parsing, the document hierarchy cannot be located and different parts of the data of the same document cannot be accessed at the same time (because line by line parsing, when parsing to line N, line N-1 has been released and can no longer be operated).
  • You cannot know the hierarchy of the element when the event occurs. You can only maintain the parent / child relationship of the node yourself
  • Read only parsing mode, unable to modify the content of XML document

2.DOM parsing
It is the official W3C standard that represents XML documents in a platform and language independent manner. Analyzing this structure usually needs to load the whole document and establish a document tree model in memory. Programmers can complete data acquisition, modification, deletion and other operations by operating the document tree.
advantage:

  • The document is loaded in memory, allowing changes to the data and structure.
  • The access is bidirectional, and the data can be parsed in both directions at any time
    Disadvantages:
  • All documents are loaded in memory, which consumes a lot of resources

3.JDOM analysis
The purpose is to become a Java specific document model, which simplifies the interaction with XML and is faster than using DOM. As it is the first Java specific model, JDOM has been vigorously promoted and promoted.
The JDOM document states that its purpose is to "solve 80% of Java or XML problems with 20% (or less) effort"
advantage:

  • Using concrete classes instead of interfaces simplifies the DOM API.
  • A large number of Java collection classes are used to facilitate Java developers
    Disadvantages:
  • No good flexibility
  • The performance is not so excellent

4.DOM4J parsing
It is an intelligent branch of JDOM, which combines many functions beyond the basic XML document representation, including integrated XPath support, XML Schema support and event-based processing for large documents or streaming documents. It also provides options for building document representation. DOM4J is a very excellent Java XML API with excellent performance, powerful functions and extremely easy to use. At the same time, it is also an open source software. Now you can see that more and more Java software are using DOM4J to read and write XML.
At present, DOM4J is widely used in many open source projects, such as Hibernate

DOM4J parsing XML

Steps:

  1. Import the jar file Dom4j jar
  2. Create an input stream that points to an XML file
    FileInputStream FIS = new FileInputStream ("address of XML file");
  3. Create an XML reader object
    SAXReader str = new SAXReader();
  4. Use the read tool object to read the input stream of the XML document, and to the document object
    Document doc = sr.read(fis);
  5. Get the root element object in the XML document through the document object
    Element root = doc.getRootElement();

Document object document

It refers to the entire XML document loaded into memory
Common methods:

  1. Get the root element object in the XML document through the document object
    Element root = doc.getRootElement();
  2. Add root node
    Element root = doc.addElement("root node name");

Element object element

Refers to a single node in an XML document.
common method

  1. Get node name
    String getName();
  2. Get node content
    String getText();
  3. Set node content
    String setText();
  4. Obtain the first child node object matching the name according to the child node name
    Element element(String child node name);
  5. Get all child node objects
    List<Element> elements();
  6. Gets the attribute value of the node
    String attributeValue(String attribute name);
  7. Get the contents of child nodes
    String elementText(String child node name);
  8. Add child node
    Element addElement(String child node name);
  9. Add attribute
    Void addAttribute(String attribute name, String attribute value);

Resolve local file cases:

public class Demo1 {
    public static void main(String[] args) throws IOException, DocumentException {
        //1. Get input stream
        FileInputStream fis = new FileInputStream("E:\\Demo1.xml");
        //2. Create an XML reading object and read XML into memory
        SAXReader sr = new SAXReader();
        //3. Create a document object and receive an xml file, that is, doc represents an xml file
        Document doc = sr.read(fis);
        //4. Get the root element from the document
        Element root = doc.getRootElement();
        //5. Start parsing elements
        System.out.println(root.getName());
        List<Element> list = root.elements();
        for (Element e:list) {
            //Gets the content of the attribute id of the book element
            System.out.println(e.attributeValue("id"));
            //Output the contents of the child element name under the book element
            System.out.println( e.elementText("name"));
            //Output the contents of the child element info under the book element
            System.out.println( e.element("info").getText());
            System.out.println("----------------");
        }
        fis.close();
    }
}

Analyze network file cases:

public class Demo2 {
    public static void main(String[] args) throws IOException, DocumentException {
        String phone = "13852869854";
        //1. Get the input stream of XML resource
        URL url = new URL("http://apis.juhe.cn/mobile/get?%20phone="+phone+"&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253");
        //2. Get the input stream of this URL resource
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        //3. Create a read object
        SAXReader sr = new SAXReader();
        //4. Read the XML data and obtain the document object
        Document doc = sr.read(is);
        //5. Get root node
        Element root = doc.getRootElement();
        //Get the query result code of the child node resultcode of the root node
        String resultcode = root.elementText("resultcode");
        //Determine whether the code is equal to 200
        if("200".equals(resultcode)){
        	//The name of the output root node
            System.out.println(root.getName());
            //Get the result of the child node under the root node
            Element result = root.element("result");
            //Get the contents of the province node and the city node under the result node
            String province = result.elementText("province");
            String city = result.elementText("city");
            if(city.equals(province)){
                System.out.println("The mobile phone number comes from a municipality directly under the Central Government:"+city);
            }else{
                System.out.println("Mobile number from"+province + city);
            }
        }else{
            System.out.println("Parsing failed, please enter the correct mobile phone number");
        }
    }
}

Parsing XML with DOM4J-XPATH

Path expression

Quickly find an element or group of elements through a path
Path expression:

  1. /: find from root node
  2. //: find descendant nodes from the location of the node initiating the lookup***
  3. .: find the current node
  4. ...: find parent node
  5. @: select an attribute*
    Attribute usage:

[@ property name = 'value']
[@ attribute name > 'value']
[@ attribute name < 'value']
[@ attribute name! = 'value']
books: Path: / / book[@id = '1'] / / name
books
book id=1 name info
book id=2 name info

Use steps

Two methods of Node class are used to complete the search:
(Node is the parent interface of Document and Element)
Method 1// Find a matching single node according to the path expression
Element e = selectSingleNode("path expression");
Method 2
List < element > ES = selectnodes ("path expression");
Case:

 public class Demo3 {
    public static void main(String[] args) throws IOException, DocumentException {
        //1. Get input stream
        FileInputStream fis = new FileInputStream("E:\\Demo1.xml");
        //2. Create an XML reading object and read XML into memory
        SAXReader sr = new SAXReader();
        //3. Create a document object and receive an xml file, that is, doc represents an xml file
        Document doc = sr.read(fis);
        Node s = doc.selectSingleNode("//book[@id='1001']//info");
        System.out.println(s.getText());
    }
}

Generate XML using Java

Steps:

  1. Through the document helper, create an empty document object document doc = documenthelper createDocument();
  2. Add a root node to the document object
    Element root = doc.addElement("root node name");
  3. Enrich our child nodes through the root node object root
    Element e = root.addElement("element name");
  4. Create a file output stream for storing XML files
    FileOutputStream fos = new FileOutputStream("location to store");
  5. Convert the file output stream to an XML document output stream
    XMLWriter xw = new XMLWriter(fos);
  6. Write a document
    xw.write(doc);
  7. Release resources
    xw.close();
    case
public class Demo5 {
    public static void main(String[] args) throws IOException {
        //1. Create a document object through the document helper
        Document doc = DocumentHelper.createDocument();
        //2. Create root node
        Element books = doc.addElement("books");
        //3. Enrich child nodes through root nodes
        for(int i =0;i<100;i++){
            Element book = books.addElement("book");
            Element name = book.addElement("name");
            name.setText(i+"plant apples");
            Element info = book.addElement("info");
            info.setText(i+"Story of");
            book.addAttribute("id",100+i+"");
        }
        //4. Create an output stream of a file
        FileOutputStream fos = new FileOutputStream("D:\\book.xml");
        //5. Convert the output stream to XML output stream
        XMLWriter xw = new XMLWriter(fos);
        //6. Write out the document
        xw.write(doc);
        //7. Close resources
        xw.close();
    }
}

Use of XStream

Quickly convert objects in java into XML strings
Use steps:

  1. Create XStream object
    XStream x = new XStream();
  2. Modify the node name generated by the class (the default node name is package name. Class name)
    x.alias("node name", class name. class);
  3. Pass in an object and generate an XML string
    String = x.toxml (object);

case

Person p = new Person(1001,"Zhang San","18");
XStream x = new XSteam();
x.alias("person",Person.class);
String xml = x.toXML(p);
System.out.println(xml);

JSON

Introduction:
JSON: Javascript object notation is a lightweight data exchange format

Object format

a copy of books
	title
	brief introduction

java:
class Book{
private String name;
private String info;
get/set...;
}
Book b = new Book();
b.setName("Golden Apple");
b.setInfo("Apple planting");
...

js:
var b = new Object();
b.name = "Golden Apple";
b.info = "plant apples";

XML:
<book>
< name > Golden Apple < / name >
< info > grow apples < / Info >
</book>

JSON:
{
"name": "Golden Apple",
"info": "planting apples"
}

In JSON, an object is represented by a brace, which describes the attributes of the object and describes the attributes of the object through key value pairs (it can be understood that the brace contains key value pairs.)
Format:
Key values are connected by colons, and multiple key value pairs are separated by commas.
The key of the key value pair should be enclosed in quotation marks (generally, when the key is parsed in Java, an error will be reported if the key does not use quotation marks, but JS can parse correctly.)
The value of a key value pair can be any type of data in JS

Array format

It can be nested with objects in JSON format
[element 1, element 2...]

case

{
	"name":"Li Junwei",
	"age":"6",
	"pengyou":["Zhang San","Li Si","Wang Wu",{
		"name":"wild horse",
		"info":"Like a wild horse"
	}],
	"heihei":{
		"name":"glaive ",
		"length":"40m"
	}
}

Java and JSON

Do what?
Quickly convert objects in Java to JSON format strings.
Converts a string in JSON format to a Java object.

At present, Java officials do not provide JSON parsing tool classes for JDK, so at present, we generally use Google's Gson and Ali's fastjason to parse JSON format data

Gson

Let's write a Book class for the demonstration of the next case, including three attributes: ID, name and info

public class Book {
    private String id;
    private String name;
    private String info;
Converts an object to a string in JSON format

1. Import jar package
2. Write the following code where the JSON string needs to be converted:
String json = new Gson(). Tojson (object to convert)
Case: converting book object to JSON

public class Demo1 {
    public static void main(String[] args) {
        //1. Create GSON object
        Gson g = new Gson();
        Book b = new Book("100","Golden Apple","It's so happy to plant apples");
        //2. Convert the object to string data in JSON format
        String s =g.toJson(b);
        System.out.println(s);
    }
}

Output:

{"id":"100","name":"Golden Apple","info":"It's so happy to plant apples"}

 
  • 1
Convert JSON strings to objects

1. Introduce jarb package
2. Write the following code where Java objects need to be converted:
Object = new gson() Fromjson (JSON string, object type. class)
Case: converting JSON string to Book object

public class Demo2 {
    public static void main(String[] args) {
    	//Create a JSON parsing tool class object
        Gson g = new Gson();
        //Call the fromjason method to parse the string and return a book object
        Book b = g.fromJson("{\"id\":\"100\",\"name\":\"Golden Apple\",\"info\":\"It's so happy to plant apples\"}",Book.class);
        //Print the properties of the object
        System.out.println(b.getId());
        System.out.println(b.getName());
        System.out.println(b.getInfo());
    }
}

output

100
 Golden Apple
 It's so happy to plant apples
Convert JSON strings to Map collections

1. Import jar package
2. Write the following code where the Map set needs to be converted
HashMap data = new Gson(). From JSON (JSON string to be converted, HashMap.class);
Case: converting a JSON string into a Map collection

public class Demo3 {
    public static void main(String[] args) {
        Gson g = new Gson();
        HashMap hm = g.fromJson("{\"id\":\"100\",\"name\":\"Golden Apple\",\"info\":\"It's so happy to plant apples\"}", HashMap.class);
        //Print the corresponding value according to the id key
        System.out.println(hm.get("id"));
    }
}

output

100

Note: when the JSON contains an array, the converted result is not an array type, but an ArrayList collection
example

public class Demo3 {
    public static void main(String[] args) {
        Gson g = new Gson();
        HashMap hm = g.fromJson("{\"id\":\"100\",\"name\":\"Golden Apple\",\"info\":\"It's so happy to plant apples\",\"color\":[\"red\",\"blue\"]}", HashMap.class);
        System.out.println(hm.get("color"));
        System.out.println(hm.get("color").getClass());
    }
}

output

[red, blue]
class java.util.ArrayList

Fastjson

Convert object to JSON string

1. Introduce JAR package
2. Write the following code where the JSON string needs to be converted
String json = JSON. Tojsonstring (object to be converted);
Case: converting book object to JSON string

public class Demo4 {
    public static void main(String[] args) {
        Book b = new Book("1002","Tang Poetry","The moon shines in front of the window");
        //Directly call the toJSONString method of the JSON class library
        String json = JSON.toJSONString(b);
        System.out.println(json);
    }
}

output

{"id":"1002","info":"The moon shines in front of the window","name":"Tang Poetry"}
Convert JSON strings to objects

1. Import jar package
2. Write the following code where Java objects need to be converted
Type object name = JSON Parseobject (JSON string, type. class);
Case: converting a JSON string into a book Object

public class Demo5 {
    public static void main(String[] args) {
        Book b = JSON.parseObject("{\"id\":\"1002\",\"info\":\"The moon shines in front of the window\",\"name\":\"Tang Poetry\"}",Book.class);
        System.out.println(b.getInfo());
    }
}

output

The moon shines in front of the window
Convert JSON strings to arrays

1. Import jar package
2. Write the following code where Java objects need to be converted
List < type > List = JSON Parsearray (JSON string, type. class);
Case: convert a JSON string into an array

public class Demo5 {
    public static void main(String[] args) {
        List<String> strings  = JSON.parseArray("[\"one two three\",\"two three four\",\"three four five\"]",String.class);
        System.out.println(strings.get(1));
    }
}

output

two three four

Keywords: Java

Added by stormx on Mon, 10 Jan 2022 17:07:54 +0200