[JavaSE Column 89] Conversion of Java strings and XML data structures, efficient and flexible data transformation

Author homepage : Designer Xiao Zheng
Author brief introduction : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction : Vue, SpringBoot, WeChat applet

This article explains the concept of XML, and the conversion method of XML and string in Java, and gives sample code. XML uses tags to define data elements and attributes. Similar to HTML, XML is more versatile and flexible and can be used to represent and exchange various types of data.

Insert image description here


1. What is XML

XML is a markup language for describing and transferring structured data .

XML uses tags to define data elements and attributes , similar to HTML. Compared with HTML, XML is more versatile and flexible and can be used to represent and exchange various types of data .

Designed to transmit data rather than display it, XML is a platform- and software-independent standard that can be used to exchange data between disparate systems and applications.

XML can be used to store and transmit any type of data, including text, numerical values, images, audio, video, etc. XML also supports the definition of metadata, which can be used to describe the structure, constraints and semantics of data.

XML uses start and end tags to define elements, for example:

<person>John</person>

Elements can have attributes, which are used to provide more information about the element, for example:

<person age="25">John</person>

XML also supports nested elements, where elements can be nested within other elements to form a hierarchy.

The main difference between XML and HTML is that XML is a custom markup language in which tags and semantics are defined by users, while HTML is a predefined markup language in which tags and semantics are fixed. Due to XML's versatility and flexibility, it is widely used in various fields, such as Web services, data exchange, configuration files, document storage, etc.

In summary, XML is a markup language used to describe and transmit structured data. It is versatile and flexible and can be used to exchange data between different systems and applications.

Insert image description here


2. Application scenarios of XML format

XML format is used in many fields, and students can briefly understand it.

  1. Data exchange : XML is widely used for data exchange between different systems. The protocols in Web services use XML to transmit data. Data exchange SOAPbetween enterprises also often uses XML format.B2B
  2. Configuration files : Many software and frameworks use XML format to define configuration files. By modifying the XML configuration file, you can change the behavior and settings of the application.
  3. Document Storage : XML format can be used to store documents and data. It can organize structured data such as text, images, tables, etc., and retain its hierarchical structure and semantic information.
  4. RSS and Atom subscriptions : XML formats and protocols commonly used to publish and subscribe to RSScontent Atom. This allows users to subscribe and get the latest information using a reader or other application.
  5. Web applications : XML format is widely used in Web applications. You can use XML to define the site map of the website, use XML to configure beans in the Spring framework, etc.
  6. Data storage and query : XML database stores data in XML format, and you can use query languages ​​such as XPathor to retrieve and manipulate data.XQuery
  7. Representing data structures : XML format can be used to represent and transmit various structured data such as spreadsheets, database table structures, data mapping in enterprise application integration, etc.

XML provides a standardized way to organize and represent structured data and enable data exchange and sharing between different systems and applications.

Insert image description here


3. Convert XML string to object

Students can use some libraries to convert XML strings into objects. For example, the Jackson library supports XML conversion.

First of all, make sure you have introduced the dependency of the Jackson library in the project, students need to pom.xmladd the following dependencies in the file.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.4</version>
</dependency>

Then, students can use the following code to convert the XML string into a Java object, the code is as follows.

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class XmlToObjectConverter {
    
    
    public static void main(String[] args) throws Exception {
    
    
        String xml = "<person><name>John</name><age>25</age></person>";

        // 创建XmlMapper对象
        XmlMapper xmlMapper = new XmlMapper();

        // 将XML字符串转换为Java对象
        Person person = xmlMapper.readValue(xml, Person.class);

        // 打印转换后的Java对象
        System.out.println(person);
    }
}

class Person {
    
    
    private String name;
    private int age;

    // 必须要有无参构造函数
    public Person() {
    
    }

    // getter和setter方法

    @Override
    public String toString() {
    
    
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

We first created XmlMapperthe object, which is the class in the Jackson library for working with XML. We then use xmlMapper.readValue()the method to convert the XML string to Persona object.

PersonThe class must contain a no-argument constructor and access private fields through getterthe and methods.setter

Finally, we print the transformed Personobject, and the output is Person [name=John, age=25].

Students can use the Jackson library to convert XML strings into Java objects. Of course, they can also use other XML processing libraries such as JAXB, DOMetc. to achieve the same function.

Insert image description here


4. Convert XML object to string

Students can use some libraries to convert objects to XML strings, such as using the Jackson library to convert XML objects to strings.

First of all, students need to ensure that the dependencies of the Jackson library have been introduced into the project, and the reference code is as follows.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.4</version>
</dependency>

Then, students can use the following code to convert the Java object into an XML string.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class ObjectToXmlConverter {
    
    
    public static void main(String[] args) throws JsonProcessingException {
    
    
        Person person = new Person("John", 25);

        // 创建XmlMapper对象
        XmlMapper xmlMapper = new XmlMapper();

        // 将Java对象转换为XML字符串
        String xml = xmlMapper.writeValueAsString(person);

        // 打印转换后的XML字符串
        System.out.println(xml);
    }
}

class Person {
    
    
    private String name;
    private int age;

    // 必须要有无参构造函数
    public Person() {
    
    }

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    // getter和setter方法

    @Override
    public String toString() {
    
    
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

We first created XmlMapperthe object, which is the class in the Jackson library for working with XML. We then use xmlMapper.writeValueAsString()the method to Personconvert the object to an XML string, and finally we print the converted XML string.

Students can use the Jackson library to convert Java objects into XML strings. Of course, they can also use other XML processing libraries such as JAXB, DOMetc. to achieve the same function.

5. XML interview questions

  1. What is XML? What does it do?
  2. What is the difference between XML and HTML?
  3. Please explain what XML parsing methods are and how they differ.
  4. Please explain the difference between DOM and SAX parsers.
  5. What is XPath? What is its role in XML parsing?
  6. What are DTDs and XSDs? What's the difference between them?
  7. How to parse an XML file using DOM in Java?
  8. How to parse an XML file using SAX in Java?
  9. How to parse an XML document using XPath in Java?
  10. How to generate XML documents in Java?
  11. What is XML serialization and deserialization? How to implement XML serialization and deserialization in Java?
  12. Introduce the JAXB framework and its role in XML processing.
  13. Please explain the concept of XML namespaces and their role in XML.
  14. What is XSLT? What does it do?
  15. How to transform an XML document using XSLT in Java?

6. Summary

This article explains the concept of XML, as well as the conversion method of XML and strings in Java, and gives sample code. In the next blog, we will explain how to use JDBC to connect to the MySQL database in Java.

Insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132531514