What is XML?

XML: Extensiable Markup Language is called extensible Markup Language

A brief history of XML:

  • gml->sgml->html->xml
  • GML (General Markup Language) – data specification for communication between different machines
  • SGML (Standard Common Markup Language)
  • HTML (Hypertext Markup Language)

Why do we need to use XML?

  • ① Before we had XML, we used String as communication between two programs! Now the question is, if we’re transferring data with a relational structure, what does String look like? String is not good at relational data, and there will be some ambiguity when describing it. The relational data is shown below:

  • 2.The HTML language is inherently flawed:
    • ** tags are fixed and cannot be customized. What markup can be used in HTML
    • The HTML tag itself lacks meaning (tr tag can put anything inside, not standard! !).
    • HTML is not truly internationalized

XML files solve the above problems, if you use XML to describe the relationship of the above images, it is very simple!


	<?xml version="1.0" encoding="UTF-8" ? >
	<China>
	    <Beijing>
	        <haidian></haidian>
	        <fengtai></fengtai>
	    </Beijing>
	    <hunan>
	        <changsha></changsha>
	        <yueyang></yueyang>
	    </hunan>
	    <hubei>
	        <wuhan></wuhan>
	        <jingzhou></jingzhou>
	    </hubei>
	</China>


Copy the code

XML files can also be opened using a browser:

We can see that XML can describe very complex data relationships


The purpose of the XML

① configuration files (example: Tomcat web. XML,server.xml……) XML can describe the relationships between programs very clearly

② : data transmission between programs, XML format is universal, can reduce the complexity of data exchange!

③ : Act as a small database, if our data sometimes need to be manually configured, then XML act as a small database is a good choice, the program read XML file is obviously faster than reading the database!


Technical architecture for XML #

XML is designed to do “nothing.” XML data or XML documents are only used to organize and store data. Other operations that generate, read, transfer, access, and so on have nothing to do with XML itself!

As a result, to manipulate XML, you need to use technologies other than XML:

  • Rules FOR XML: Nowadays DTD or Schema technology is commonly used, and of course Schema technology is more advanced!
  • Parsing XML data: DOM or SAX techniques are commonly used, each with its own advantages
  • Provide style: XML is generally used to store data, but the designers were very ambitious and wanted to display data as well (but no one used XML to display data). Thus came XSLT(eXtensiable Stylesheet Transformation), the extensible style Transformation Language

The XML syntax:

Document declaration:

  • The XML declaration is placed in the first line of XML

  • Version – version

  • Encoding –

  • Standalone — Used independently — Default is no. Standalone indicates whether the XML stands alone or, if yes, that the XML document stands alone and cannot refer to an external DTD specification file. If it is no, the XML document is not standalone, meaning that external DTD specification documents can be referenced.

  • Correct document declaration format, property position cannot be changed!


	<?xml version="1.0" encoding="utf-8" standalone="no"? >

Copy the code

The element

Let’s start with the concept that elements and tags refer to the same thing in XML! Don’t be fooled by the different names!

Elements to note:

  • Occurrences of whitespace and newlines in XML elements are treated as element content
  • Each XML document must have one and only one root element
  • The element must be closed
  • Case sensitivity
  • Cannot cross nest
  • You can’t start with a number

This might seem like a lot to note, but just remember: XML syntax is canonical! Don’t scribble!


attribute

Attributes are part of XML elements, and the naming conventions are the same as for XML elements!


	<! -- Attribute name = name, attribute value = China -->
	<China name="china">

	</China>


Copy the code

annotation

Comments are the same as HTML comments


	<! ---->

Copy the code

CDATA

When you write an XML file, some content may not be parsed by the parsing engine, but treated as raw content. In this case, you can put the content in the CDATA section, and the XML parser will not process the content in the CDATA section, but simply output it as it is

Grammar:

<! [CDATA[... contents]]>Copy the code

Escape character

Some individual characters can also be escaped if they want to display their original style.

A processing instruction

Processing instruction, abbreviated as PI (Processing Instruction). Processing instructions are used to instruct the parsing engine how to parse the content of the XML document.

Such as:

In an XML document, you can use the XML-Stylesheet directive to inform the XML parsing engine and apply CSS files to display the content of the XML document.

	<?xml-stylesheet type="text/css" href="1.css"? >

Copy the code
  • XML code:



	<?xml version="1.0" encoding="UTF-8" ? >
	<?xml-stylesheet type="text/css" href="1.css"? >
	
	<china>
	    <guangzhou>Guangzhou</guangzhou>
	    <shenzhen>shenzhen</shenzhen>
	</china>


Copy the code
  • The CSS code:
	
	
	guangzhou{
	    font-size: 40px;
	}

Copy the code
  • Effect:


XML APIS in the JDK

① : JAXP (The Java API For XML Processing) : mainly responsible For parsing XML

(2): Java Architecture for XML Binding (JAXB): mainly responsible for mapping XML to Java objects

What is XML parsing

As mentioned in the previous XML chapter, XML is designed to do “nothing.” XML is only used to organize and store data, and other operations that generate, read, transfer, and so on have nothing to do with XML itself!

XML parsing is reading XML data!


XML parsing

There are two ways to parse XML:

① : DOM (Document Object Model) Document Object Model, is a way recommended by W3C to parse XML

Sax (Simple API For XML), which is the standard of the XML community and supported by almost all XML parsers!

XML parsing operation

As you can easily see from the above figure, the application does not operate on the XML document directly. Instead, the XML document is analyzed by the XML parser, and the application then operates on the analysis results through the DOM interface or SAX interface provided by the XML parser, thereby indirectly achieving access to the XML document!

The relationship between common parsers and parsing development packages is as follows:


Why are there three development kits?

  • The JAXP development package comes with the JDK and you do not need to import the development package.
  • Because Sun’s JAXP wasn’t perfect, Jdom was developed. If you use Jdom for XML parsing, you need to import the development package
  • Dom4j was developed by a group of Jdom developers due to a split among Jdom developers. XML parsing using Jdom requires importing development packages (dom4J is the most popular now!).

jaxp

While JAXP isn’t nearly as good at parsing XML as dom4J and making it easier to develop, jaxP is a built-in JDK development package that needs to be learned!

DOM parsing operations

DOM parsing is an object-based API that loads the contents of XML into memory and generates a model corresponding to the contents of an XML document! When parsing is complete, a DOM object tree corresponding to the structure of the XML document is generated in memory, so that the document can be manipulated as nodes according to the structure of the tree!

Simply put: DOM parsing loads XML documents into memory, generating DOM tree elements in the form of objects! We can manipulate XML documents by manipulating these objects!

  • The following diagram illustrates how to generate a DOM tree corresponding to the content of an XML document!


Since the data of an XML document is relational, the nodes of the generated DOM tree are also relational:

  • The node above a node is the parent of that node.
  • The nodes below a node are the children of that node.
  • Nodes at the same level that have the same parent are siblings.
  • The collection of nodes at the next level of a node is the node descendant.
  • The parent node, the grandfather node, and everything above the node is the node’s ancestor.

There are several core manipulation interfaces in DOM parsing:

  • Document [represents the entire XML Document, through the Document node can access all elements of the XML file content!]
  • Node the Node Node is almost equivalent to the ordinary Java class Object in THE XML operation interface, and many core interfaces implement it, as you can see in the diagram below!
  • NodeList [stands for a collection of nodes, usually a collection of neutron nodes of a node!
  • NameNodeMap specifies the one-to-one mapping between a set of nodes and their unique names. It is used to represent attribute nodes.

Relationship diagram between nodes:

  • Some people may find it hard to understand why the Document interface is smaller than the Node interface. If really think impassability: the somebody else all designed like this, you have seed need not!! (Kidding…..)

Ok, without bb, let’s use Dom to parse XML documents.

  • XML document code

	<?xml version="1.0" encoding="UTF-8" ? >
	<china>
	    <guangzhou >Guangzhou</guangzhou>
	    <shenzhen>shenzhen</shenzhen>
	    <beijing>Beijing</beijing>
	    <shanghai>Shanghai</shanghai>
	</china>


Copy the code
  • According to the flow chart of XML parsing, we first need to get the parser object!


	public class DomParse {
	
	    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
	
	        //API specification: you need a factory to build parser objects, so I built a factory first!
	        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	
	        // Get the parser object
	        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
	
	        // Get the stream object that parses the XML document
	        InputStream inputStream = DomParse.class.getClassLoader().getResourceAsStream("city.xml");
	
	        // Parse the XML Document and get the Document object representing the XML Document!Document document = documentBuilder.parse(inputStream); }}Copy the code
  • What is the purpose of parsing the contents of an XML document? If we can add, delete, change, and search XML, then we know how to use DOM parsing!

traverse

  • Let’s look at the contents of the XML document again. What if we want to iterate over it? :

  • Maybe we have two thoughts:

    • ① : Look down the content of the XML document and output what you see! This is exactly what SAX parsing does.
    • ② Divide the content of an XML document into two parts, one with child nodes and one without (element nodes!). . First of all, we determine whether it is an element node. If it is an element node, we output it. If it is not an element node, we get the set of child nodes Okay, accidentally recursing…
  • Let’s walk through the XML document and write it as a method for better reuse (and for better recursion)!


	public class DomParse {
	
	    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
	
	        //API specification: you need a factory to build parser objects, so I built a factory first!
	        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	
	        // Get the parser object
	        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
	
	        // Get the File object that parses the XML document
	        InputStream inputStream = DomParse.class.getClassLoader().getResourceAsStream("city.xml");
	
	        // Parse the XML Document and get the Document object representing the XML Document!
	        Document document = documentBuilder.parse(inputStream);
	
	        // Pass the document object representing the XML document to the list method
	        list(document);
	
	    }
	
	
	    // Let's accept Node instance objects. Polymorphic!!
	    private static void list(Node node) {
	
	        // Check if it is an element node
	        if (node.getNodeType() == Node.ELEMENT_NODE) {
	            System.out.println(node.getNodeName());
	        }
	
	        / /... If the if statement is not entered, the following nodes are definitely not element nodes, so we get a collection of child nodes
	        NodeList nodeList = node.getChildNodes();
	
	        // Iterate over the collection of child nodes
	        for (int i = 0; i < nodeList.getLength(); i++) {
	
	            // Get one of the children
	            Node child = nodeList.item(i);
	
	            / /... Check whether the child node is an element node, if it is an element node output, not an element node and then get its child node set... The recursivelist(child); }}}Copy the code
  • Effect:


The query

Now what I need to do is to read the text content of this node guangzhou!



    private static void read(Document document) {

        // Get all guangzhou nodes
        NodeList nodeList = document.getElementsByTagName("guangzhou");
        
        // Fetch the first node named Guangzhou
        Node node = nodeList.item(0);
        
        // Get the text content of the node
        String value = node.getTextContent();

        System.out.println(value);

    }

Copy the code
  • Effect:


increase

Now I want to add one more city node (Hangzhou), I need to do this:


    private static void add(Document document) {

        // Create a node to be added
        Element element = document.createElement("hangzhou");

        // Add text content to the node
        element.setTextContent("Hangzhou");

        // Get the parent node to which you want to add the node
        Node parent = document.getElementsByTagName("china").item(0);

        // Attach the node to the parent node
        parent.appendChild(element);

    }

Copy the code
  • To do this, I just added a node under the Dom tree in memory. To write the Dom tree in memory to the hard disk file, I need a converter!

  • Getting the converter is also simple:


        // To get a converter it needs a factory to build, so I'll build a factory
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        
        // Get the converter object
        Transformer transformer = transformerFactory.newTransformer();

Copy the code
  • Updating the Dom tree in memory to the transform() method in the hard disk file is a little more complicated!

  • It requires a Source instance object and a Result instance object. What are these interfaces?

  • DomSource implements the Source interface. We are using Dom parsing. If we look at the constructor, it looks like it.

  • SteamResult implements the Result interface, one might think, DomResult implements the Result interface, why not use DomResult? What we are doing now is updating the Dom tree in memory to the hard disk file using StreamResult.

  • The complete code is as follows:


    private static void add(Document document) throws TransformerException {

        // Create a node to be added
        Element element = document.createElement("hangzhou");

        // Add text content to the node
        element.setTextContent("Hangzhou");

        // Get the parent node to which you want to add the node
        Node parent = document.getElementsByTagName("china").item(0);

        // Attach the node to the parent node
        parent.appendChild(element);

        // To get a converter it needs a factory to build, so I'll build a factory
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        // Get the converter object
        Transformer transformer = transformerFactory.newTransformer();

        // Update the Dom tree in memory to hard disk
        transformer.transform(new DOMSource(document),new StreamResult("city.xml"));
    }

Copy the code
  • Effect:


The newly added node is at the end of the China node. Now I want to specify that the newly added node is at the end of the Beijing node.



    private static void add2(Document document) throws TransformerException {

        // Obtain the Beijing node
        Node beijing = document.getElementsByTagName("beijing").item(0);

        // Create new nodes
        Element element = document.createElement("guangxi");

        // Sets the text content of the node
        element.setTextContent("Guangxi");

        // Get the parent of the node to be created,
        Node parent = document.getElementsByTagName("china").item(0);

        // Insert the guangxi node before the Beijing node!
        parent.insertBefore(element, beijing);

        // Update the Dom tree in memory to the hard disk file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult("city.xml"));
        
    }

Copy the code
  • Effect:


delete

Now I want to delete the Beijing node!



    private static void delete(Document document) throws TransformerException {

        // Get the Beijing node
        Node node = document.getElementsByTagName("beijing").item(0);

        // Get the parent node and delete yourself from the parent node
        node.getParentNode().removeChild(node);

        // Update the Dom tree in memory to the hard disk file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult("city.xml"));


    }

Copy the code
  • Effect:

Modify the

Modify the text content of Guangzhou node to hello Guangzhou


    private static void update(Document document) throws TransformerException {

        // Get guangzhou node
        Node node = document.getElementsByTagName("guangzhou").item(0);

        node.setTextContent("Hello Guangzhou");

        // Update the Dom tree in memory to the hard disk file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult("city.xml"));


    }


Copy the code
  • Effect:


Action attribute

It is possible that the XML document has attribute values, now we want the attribute on the Guangzhou node

    private static void updateAttribute(Document document) throws TransformerException {

        // Get guangzhou node
        Node node = document.getElementsByTagName("guangzhou").item(0);

        // Node currently has no method to add attributes, so I'll look for its subclass Element
        Element guangzhou = (Element) node;

        // Set a property, modify it if it exists, create it if it doesn't!
        guangzhou.setAttribute("play"."gzchanglong");

        // To remove the attribute, use the removeAttribute() method


        // Update the Dom tree in memory to the hard disk file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult("city.xml"));


    }

Copy the code
  • Effect:


SAX parsing

SAX uses a sequential pattern for access and is a fast way to read XML data. When the SAX parser operates, it fires a series of events called SAX. Parsing XML files by means of event processing and parsing XML documents by SAX involves two parts: parser and event handler

Sax is a push-like mechanism. You create a SAX parser that tells you (pushes events to you) when it finds something in an XML document. It’s up to the programmer to decide what to do with it.

When the parser resolves to
element header! That is: when a SAX parser is used to scan an XML Document (that is, a Document object) at the beginning and end of the XML Document, as well as at the beginning and end of the element, events are triggered, and corresponding methods are called according to the different events!


Let’s get a SAX parser first!


        To get the parser object, I need to build a factory, so I built a factory
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        
        // Get the parser object
        SAXParser saxParse = saxParserFactory.newSAXParser();


Copy the code
  • When you call the parsing method that parses an object, you need more than just the path to the XML document! You also need an event handler!

  • Event handlers are written by our programmers, which inherit DefaultHandler classes and override the following five methods:

    @Override
    public void startDocument(a) throws SAXException {
        super.startDocument();
    }

    @Override
    public void endDocument(a) throws SAXException {
        super.endDocument();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
    }

Copy the code
  • Get the parser and call the code that parses the XML document:


    public static void main(String[] args) throws Exception{

        To get the parser object, I need to build a factory, so I built a factory
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();

        // Get the parser object
        SAXParser saxParse = saxParserFactory.newSAXParser();

        // Get the stream object of the XML document
        InputStream inputStream = SAXParse.class.getClassLoader().getResourceAsStream("city.xml");

        saxParse.parse(inputStream, new MyHandler());

    }

Copy the code
  • Event handler code:

	public class MyHandler extends DefaultHandler {
	    @Override
	    public void startDocument(a) throws SAXException {
	        System.out.println("I'm going to scan !!!!");
	    }
	
	    @Override
	    public void endDocument(a) throws SAXException {
	
	        System.out.println("I'm done !!!!");
	    }
	
	    @Override
	    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

			// To parse the contents of node attributes, it's as simple as using the Attributes variable!

			// Print the name of the node!
	        System.out.println(qName);
	    }
	
	    @Override
	    public void endElement(String uri, String localName, String qName) throws SAXException {
	
	        System.out.println(qName);
	    }
	
	    @Override
	    public void characters(char[] ch, int start, int length) throws SAXException {
	
	        System.out.println(newString(ch,start,length)); }}Copy the code
  • We found that the code for the event handler was very simple, and then it was that easy to walk through the entire XML document!

  • If you want to query the content of a single node is also very simple yo! Just check if the names are the same in the startElement() method!

  • Now I just want to check the content of Guangzhou node:


    // Define an identifier that specifies the contents of a node to be queried
    boolean flag = false;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

        // If the node name is Guangzhou, I will output it and set the identifier to true
        if (qName == "guangzhou") {
            System.out.println(qName);
            flag = true; }}@Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        // I output the content of the text only if flag is true
        if (flag == true) {
            System.out.println(newString(ch, start, length)); }}@Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        // Do not forget to change the identifier to false when executing at the end of the element
        if (qName == "guangzhou" && flag == true) {
            System.out.println(qName);
            flag = false; }}Copy the code
  • Effect:


The difference between DOM and SAX parsing:

DOM parsing reads the entire XML document and forms a DOM tree in memory, making it easy to add, delete and modify the content of an XML document. But if the CONTENT of the XML document is too large, then you can run out of memory!

SAX parsing adopts partial reading and can deal with large files, but it can only parse the files from beginning to end in order, and does not support the operation of adding, deleting and modifying files

DOM parsing is very different from SAX parsing, and it’s pretty clear when to use DOM or SAX.


dom4j

Dom4j is an excellent Java XML API with excellent performance, power, and ease of use.

Why dom4J

  • Dom disadvantages: Relatively memory intensive

  • Sax disadvantage: XML files can only be read, can not modify, add, delete

  • Dom4j: Both for efficiency and CRUD operations

Since Dom4J is not a Sun product, we need to import the development package to develop dom4j


Get a parser for Dom4j

  • Using Dom4j to add, delete, modify, and query XML documents requires a Dom4j parser

        // Get the parser
        SAXReader saxReader = new SAXReader();

        // Get the stream object of the XML file
        InputStream inputStream = DOM4j.class.getClassLoader().getResourceAsStream("1.xml");

        // Read the XML file through the parser
        Document document = saxReader.read(inputStream);
        

Copy the code

Get the Document object

As we all know, Document stands for XML Document, and we usually start with the Document object to do CRUD operations!

There are three ways to get a Document object:

① : Read the XML file, obtain the Document object (this is most commonly used)

SAXReader reader = newSAXReader (); Document document = reader.read(new File("input.xml"));

Copy the code

② : Parse the TEXT in XML form and get the Document object

	
	String text = "<members></members>";
	Document document=DocumentHelper.parseText(text);


Copy the code

③ : Actively create the Document object.


Document document =DocumentHelper.createDocument();

// Create root node
Element root = document.addElement("members");
Copy the code

Important CRUD words:

Read XML Document data, are through the Document to obtain the root element, and then through the root element to obtain other nodes, so as to operate!

If the XML structure has multiple layers, you need to fetch it layer by layer!

The query


    @Test
    public void read(a) throws DocumentException {

        // Get the parser
        SAXReader saxReader = new SAXReader();

        // Get the stream object of the XML file
        InputStream inputStream = dom4j11.class.getClassLoader().getResourceAsStream("1.xml");
   
        // Read the XML file through the parser
        Document document = saxReader.read(inputStream);

        // Get the root node
        Element root = document.getRootElement();

        // Get the name node
        Element name = root.element("name");

        // Get the attributes of the name node or the text content of the name node.
        String text = name.getText();

        String attribute = name.attributeValue("littleName");

        System.out.println("The text is:" + text);
        System.out.println("The property content is:" + attribute);
        
    }


Copy the code
  • The XML file is as follows:

	<?xml version="1.0" encoding="UTF-8" ? >
	     <person>
	    <name littleName="fucheng">zhongfucheng</name>
	    <age>20</age>
	</person>


Copy the code
  • Effect:

  • Multi-layer query:

        // Get the root node
        Element root = document.getRootElement();

        // Get nodes layer by layer
        Element element = root.element("guangdong").element("guangzhou").element("luogang");

        String value = element.getText();

        System.out.println(value);

Copy the code
  • XML files and results:


increase

In DOM4j to write the DOM tree in memory to the hard disk file, also need to have converter support!

Dom4j provides XMLWriter for updating XML documents. Generally, when creating XMLWriter, we give two parameters, one is Writer and the other is OutputFormat

So what does this OutputFormat do? You specify the format and encoding format for writing back to XML. The Transformer class, which uses DOM parsing under JAXP, updates the DOM tree in memory to the file disk without formatting. Go back and see! This OutputFormat allows us to update XML documents with formatting!


        // Create a formatted object
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();

        // Set the encoding to gb2312. The default encoding is GB2312.
        outputFormat.setEncoding("UTF-8");

        // Create an XMLWriter object
        XMLWriter xmlWriter = new XMLWriter(new FileWriter("2.xml"), outputFormat);

        // The XMLWriter object writes document
        xmlWriter.write(document);

        / / close the flow
        xmlWriter.close();

Copy the code
  • Create a name node under the person node. The complete code is as follows:


	@Test
    public void add(a) throws Exception {

        // Get the parser
        SAXReader saxReader = new SAXReader();

        // Get the stream object of the XML file
        InputStream inputStream = dom4j11.class.getClassLoader().getResourceAsStream("1.xml");

        // Read the XML file through the parser
        Document document = saxReader.read(inputStream);

        // Create a new node and set the text content for the node
        Element newElement = DocumentHelper.createElement("name");
        newElement.setText("ouzicheng");

        // Get the root element
        Element root = document.getRootElement();

        // Hang the newly created name node below the root node
        root.add(newElement);

        // Create a formatted object
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();

        // Set the encoding to gb2312. The default encoding is GB2312.
        outputFormat.setEncoding("UTF-8");

        // Create an XMLWriter object
        XMLWriter xmlWriter = new XMLWriter(new FileWriter("2.xml"), outputFormat);

        // The XMLWriter object writes document
        xmlWriter.write(document);

        / / close the flow
        xmlWriter.close();


    }

Copy the code
  • The effect is as follows, is formatted!


Add node at the specified location! Now all I want is to add nodes in front of the age property!


        Create a new node
        Element element = DocumentHelper.createElement("name");
        element.setText("ouzciheng");

        // Get all node elements under person!
        List list = document.getRootElement().elements();

        // Adds the node to the specified location
        list.add(1, element);


Copy the code
  • Effect:



Modify the

  • I won’t post the code for XMLWriter and getting the Document object, it’s all the same!

        // Get the age element
        Element age = document.getRootElement().element("age");
        age.setText("9999");


Copy the code
  • The effect is as follows:


delete

  • I won’t post the code for XMLWriter and getting the Document object, it’s all the same!

        // Get the age node
        Element age = document.getRootElement().element("age");

        // Get the parent node of the age node, use the parent node remove to remove the age node!
        age.getParent().remove(age);

Copy the code
  • Effect:


XPATH

What is the XPATH

XPath is a language for finding information in XML documents. XPath is used to navigate through elements and attributes in AN XML document.

Why do we need XPATH

When we used dom4j above, to get a node, we always start from the root node and go down the layer, which is a bit of trouble!

If we use XPATH, it’s very easy to get the XML nodes!


Quick start

To use XPATH, you need to import the development package jaxEN-1.1-beta-7, so let’s take a look at the official documentation to get started.

  • XPATH documentation is very international, even in Chinese

  • There are so many examples in the XPATH documentation that it’s easy to learn, just look at them!

  • Let’s use XPATH to read information from an XML file. The XML document looks like this:

  • Before, we first obtained the root node, then obtained the Guangdong node, then obtained the Guangzhou node, and then read the Tianhe node or Luogang node. Now let’s see how convenient XPATH can be!

        // Get the luogang node directly
        org.dom4j.Node node =  document.selectSingleNode("//luogang");

        // Get the contents of the node
        String value = node.getText();

        System.out.println(value);

Copy the code
  • Effect:

What types of nodes to get, and how XPATH strings should match, are documented, and won’t be discussed here. !


If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat can follow the wechat public account :Java3y