XML is that simple

Time:2019-8-7

What is XML?

XML: Extensible Markup Language is called Extensible Markup Language

A brief history of XML:

  • gml->sgml->html->xml
  • GML (Universal Markup Language) – Data Specification for Communication between Different Machines
  • SGML (Standard Universal Markup Language)
  • HTML (Hypertext Markup Language)

Why do we need to use XML?

  • Before we had XML, we used String as a communication between two programs. Now the question arises. If we are transmitting data with relational structure, how can String be expressed? String is not good at relational data, and it will inevitably be ambiguous when it is described! Relational data is shown below.

XML is that simple

  • The HTML language itself is flawed

    • Tags are fixed and cannot be customized. What tags can only be used in HTML
    • HTML tags themselves lack meaning (anything in tr tags can be put in, not standardized! !
    • HTML does not really internationalize

The XML file solves the above problems. If we use XML to describe the relationship between the above pictures, 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>

XML files can also be opened using browsers:

XML is that simple

We can find that XML can describe very complex data relationships.


Use of XML

①:Configuration files (example: Tomcat’s web. xml, server. xml…), XML can clearly describe the relationship between programs.

②:The format of XML is universal for data transmission between programs, which can reduce the complexity of data exchange.

③:Acting as a small database, if our data sometimes needs to be configured manually, then XML is a good choice to act as a small database. It is obviously faster for programs to read XML files directly than to read the database.


Technical Architecture of XML

XML is designed to “do nothing”. XML data or XML documents are only used to organize and store data. In addition, data generation, reading, transmission, access and other operations are not related to XML itself!

So if you want to manipulate XML, you need to use technologies other than XML.

  • Rule for XML: DTD or Schema technology is commonly used now, of course, Schema technology is more advanced!
  • Parsing XML data: DOM or SAX technologies are commonly used, each with its own advantages
  • Providing Styles: XML is generally used to store data, but designers are ambitious and want to display data (but no one uses XML to display data), so there is XSLT (eXtensible Stylesheet Language Transformation) Extensible Style Transform Language.

XML grammar:

Document declaration:

  • XML declarations are placed on the first line of XML
  • Version – Version
  • Encoding — encoding
  • Standalone — used independently — defaults to No. Standalone indicates whether the XML is independent, and if yes, it represents the XML document independently and cannot refer to an external DTD specification file; if no, the XML document is not independent, indicating that it can refer to an external DTD specification document.
  • Proper document declaration format, attribute location can not be changed!

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

element

First of all, I will explain a concept here:In XML, elements and tags refer to the same thing! Don’t be confused by different names!

Notable points in elements

  • Spaces and newlines that appear in XML elements are treated as element content.
  • Each XML document must have and have only one root element
  • Elements must be closed
  • Case-sensitive
  • Can’t cross nest
  • You can’t start with numbers.

There seems to be a lot to be noticed, but in fact, just remember:The grammar of XML is standard! Don’t scribble!


attribute

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

<! -- The name of the attribute and the value of the attribute are China-->.
    <China name="China">

    </China>

Notes

Annotations are the same as HTML annotations


    <!---->

CDATA

When writing an XML file, some content may not want to be parsed and executed by the parsing engine, but processed as raw content. In this case, you can put these contents in the CDATA area. For the contents in the CDATA area, the XML parser will not process them, but will output them directly as they are.

Grammar:

<![CDATA[
        Content
    ]]>

Escape character

For some individual characters, if you want to show their original style, you can also use the form of escape to deal with them.

XML is that simple

Processing instructions

Processing instructions, referred to as PI (processing instruction). Processing instructions are used to direct the parsing engine to parse the content of an XML document.

For example:

The xml-stylesheet directive can be used in the XML document to notify the XML parsing engine and to display the content of the XML document with the CSS file.

    <?xml-stylesheet type="text/css" href="1.css"?>
  • 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>
  • CSS code:
    
    
    guangzhou{
        font-size: 40px;
    }
  • Effect:

XML is that simple


XML API in JDK

JAXP (The Java API for XML Processing): Primarily responsible for parsing XML

(2) JAXB (Java Architecture for XML Binding): 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. In addition, the operations of data generation, reading, transmission 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:

(1) DOM (Document Object Model) Document Object Model is a method recommended by W3C to parse XML.

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

XML parsing operation

XML is that simple

It’s easy to see from the figure above.The application program does not operate on the XML document directly, but analyses the XML document by the XML parser. Then the application program operates on the analysis result through the DOM interface or SAX interface provided by the XML parser, thus indirectly realizes the access to the XML document.

The relationships between common parsers and parsing development kits are as follows

XML is that simple


Why are there three development packages?

  • The jaxp development kit comes with JDK and does not need to be imported.
  • Because Sun’s jaxp was not perfect enough, 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 because of divergence among Jdom developers. If you use Jdom for XML parsing, you need to import the development package [dom4j is the most used now! ]

jaxp

Although the performance of jaxp in parsing XML and the simplicity of development are not as good as dom4j, howeverJaxp is a JDK built-in development package anyway, we need to learn

DOM parsing operation

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

In short:DOM parsing loads the XML document into memory, and the elements that generate the DOM tree are all in the form of objects! We can manipulate XML documents by manipulating these objects!

  • Here’s a good illustration.How to generate DOM tree corresponding to the content of XML document?

XML is that simple


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

  • A node above a node is the parent of that node.
  • A node under a node is a child of that node.
  • At the same level, the node with the same parent node is sibling.
  • The set of nodes at the next level of a node is descendant.
  • Father, grandfather nodes and all those above them are ancestors of nodes.

There are several core operational interfaces in DOM parsing:

  • Document [Represents the entire XML document, through the Document node can access all the elements in the XML file content! ]
  • Node [Node node is almost equivalent to Object of ordinary Java class in the XML operation interface, and many core interfaces implement it, as can be seen in the diagram below! ____________ ]
  • NodeList [represents a set of nodes, usually a set of neutron nodes of a node! ]
  • NameNodeMap [denotes a one-to-one correspondence between a set of nodes and their unique names, mainly used for the representation of attribute nodes (the book says it is the core operational interface, but I don’t seem to use it! Uh, uh, when I use it, I’ll fill the pit again! ]

Relational graph of nodes:

XML is that simple

  • Some people may be hard to understand.Why is the Document interface smaller than the Node interface, er, I think so: a Document consists of countless Nodes, so I can also think of Document as Node.! If you really can’t figure it out: people have designed it like this, you don’t have to!! (Joking….)

Well, instead of having more BB with you, let’s parse the XML document in a Dom way.

  • XML Document Code
<?xml version="1.0" encoding="UTF-8" ?>
    <china>
        < Guangzhou > Guangzhou < / Guangzhou >
        < Shenzhen > Shenzhen </shenzhen >
        < Beijing > Beijing < / Beijing >
        < Shanghai > Shanghai </Shanghai >
    </china>
  • According to the flow chart of XML parsing,We need to get the parser object first!
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();
    
            // Getting parser objects
            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);
            
        }
    }
  • What is the use of parsing the content of an XML document? It’s all about adding, deleting, altering and searching.As long as we add, delete and modify XML, that means we will use DOM parsing.

ergodic

  • Let’s take a look at the content of the XML document again. What should we do if we want to traverse it?

XML is that simple

  • Maybe we have two ideas.

    • (1) Looking from the top down of the content of the XML document, you can output whatever you see! [This is exactly what SAX parses do]
    • (2) Divide the content of an XML document into two parts, one with child nodes and the other without child nodes (that is, element nodes!). Firstly, we judge whether it is an element node, if it is an element node, it will output, if it is not an element node, it will get the set of sub-nodes, and then judge whether the set of sub-nodes is an element node, if it is an element node, it will output, if it is not an element node, it will get the set of sub-nodes…. Okay, it will be delivered carelessly. I’m home.
  • Let’s walk through the XML document and write it as a method for better reuse.
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();
    
            // Getting parser objects
            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 in the document object representing the XML document to the list method
            list(document);
    
        }
    
    
        // Let's accept Node type instance objects here. Polymorphism!!!
        private static void list(Node node) {
    
            // Determine whether it is an element node or not, and output directly if it is an element node.
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                System.out.println(node.getNodeName());
            }
    
            // If you don't enter the if statement, the following is definitely not the element node, so you get the set of child nodes.
            NodeList nodeList = node.getChildNodes();
    
            // Traversing the set of sub-nodes
            for (int i = 0; i < nodeList.getLength(); i++) {
    
                // Get one of the child nodes
                Node child = nodeList.item(i);
    
                //... To determine whether the child node is an element node, if it is an element node, it will output, not an element node, and then get its set of child nodes... Recursive __________.
    
                list(child);
            }
            
        }
    }
  • Effect:

XML is that simple


query

Now all I have to do is read the text content of the Guangzhou node!

private static void read(Document document) {

        // Get all the nodes named Guangzhou
        NodeList nodeList = document.getElementsByTagName("guangzhou");
        
        // Take out 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);

    }
  • Effect:

XML is that simple


increase

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

private static void add(Document document) {

        // Create additional nodes
        Element element = document.createElement("hangzhou");

        // Adding text content to nodes
        Element. setTextContent ("Hangzhou");

        // Get the parent node that needs to add the node
        Node parent = document.getElementsByTagName("china").item(0);

        // Hang the additional nodes under the parent node
        parent.appendChild(element);

    }
  • To do this, I just added a node under the memory Dom tree. To write the memory Dom tree to the hard disk file, I need a converter.
  • The acquisition converter is also very 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();
  • Updating the Dom tree in memory to the transform () method in the hard disk file is slightly more complicated.

XML is that simple

  • It needs a Source instance object and an instance object of Result. What are these two interfaces for?
  • SoI went to the API and found that DomSource implements the Source interface. Aren’t we using Dom parsing? Looking at the construction method, it feels like it!

XML is that simple

  • Steam Result implements the Result interface, and some people will also think that 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, of course Stream Result!
  • The complete code is as follows:
private static void add(Document document) throws TransformerException {

        // Create additional nodes
        Element element = document.createElement("hangzhou");

        // Adding text content to nodes
        Element. setTextContent ("Hangzhou");

        // Get the parent node that needs to add the node
        Node parent = document.getElementsByTagName("china").item(0);

        // Hang the additional nodes under 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 the hard disk
        transformer.transform(new DOMSource(document),new StreamResult("city.xml"));
    }
  • Effect:

XML is that simple


The newly added node is at the end of the China node, and now I amYou want to specify an additional node before the Beijing nodeIn this way:

private static void add2(Document document) throws TransformerException {

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

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

        // Setting the text content of the node
        Element. setTextContent ("Guangxi");

        // Gets the parent node to create the node,
        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"));
        
    }
  • Effect:

XML is that simple


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 through 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"));


    }
  • Effect:

XML is that simple

modify

Modify the text content of Guangzhou node to Guangzhou Hello

private static void update(Document document) throws TransformerException {

        // Get the 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"));


    }
  • Effect:

XML is that simple


Operational attributes

XML documents may have attribute values, so now we need attributes on the Guangzhou node

private static void updateAttribute(Document document) throws TransformerException {

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

        // Node node has no way to add attributes now, so I'm looking for its subclass, Element.
        Element guangzhou = (Element) node;

        // Set an attribute, modify it if it exists, and create it if it does not exist!
        guangzhou.setAttribute("play", "gzchanglong");

        // If you want to delete an 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"));


    }
  • Effect:

XML is that simple


SAX parsing

SAX uses a sequential pattern for access, which is a fast way to read XML data. When the SAX parser operates at that time, it triggers a series of events SAX. Using event processing to parse XML documents and SAX to parse XML documents involves two parts:Parser and Event Processor

Sax is a push mechanism. You create a Sax parser, which tells you (push events to you) when it finds content in an XML document. It’s up to the programmer to decide how to handle that content.

When the parser parses to<?xml version="1.0" encoding="UTF-8" standalone="no"?>The event is triggered when the header is declared. Resolve to<china>Element headers also trigger events! In other words:When using SAX parser to scan XML document (that is, Document object), start and end, and start and end of element will trigger events, call corresponding methods according to different events!

XML is that simple


First of all, we are still there.Get the SAX parser first.Now!

// To get the parser object, you need to build a factory, so I built a factory.
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        
        // Get the parser object
        SAXParser saxParse = saxParserFactory.newSAXParser();
  • When calling parsing methods for parsing objects, you need more than just the path of the XML document! You also need an event handler!

XML is that simple

  • Event handlers are written by our programmers. They generally inherit the DefaultHandler class and rewrite the following five methods:

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

    @Override
    public void endDocument() 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);
    }
  • Get the parser and call the parser to parse the code of the XML document:
public static void main(String[] args) throws Exception{

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

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

        // Getting Stream Objects for XML Documents
        InputStream inputStream = SAXParse.class.getClassLoader().getResourceAsStream("city.xml");

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

    }
  • Event Processor Code:
public class MyHandler extends DefaultHandler {
        @Override
        public void startDocument() throws SAXException {
            System.out.println ("I'm starting to scan!!!!!! "";
        }
    
        @Override
        public void endDocument() throws SAXException {
    
            System.out.println ("I'm over!!!!!! "";
        }
    
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

            // If you want to parse the content of node attributes, it's very simple, just through attributes variables!

            // Output node name!
            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(new String(ch,start,length));
        }
    }
  • We found that,Event processor code is very simple, and then it’s so easy to traverse the entire XML document!
  • If you want to query the content of a single node is very simple yo! Just judge whether the name is the same in the startElement () method!
  • Now I just want to query the contents of the Guangzhou node:
// Define an identifier to specify the content of a query node
    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 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 {
        // Only if flag is true can I output the content of the text.
        if (flag == true) {
            System.out.println(new String(ch, start, length));

        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        // When executing to the end of an element, don't forget to change the identifier to false
        if (qName == "guangzhou" && flag == true) {
            System.out.println(qName);
            flag = false;

        }
    }
  • Effect:

XML is that simple


The difference between DOM and SAX parsing:

DOM parses and reads the whole XML document, and forms DOM tree in memory. It is very convenient to add, delete and modify the content of the XML document. But if the content of the XML document is too large, it will lead to memory overflow!

SAX parsing uses the way of partial reading, which can handle large files, but it can only parse files from beginning to end in sequence, and does not support the operation of adding, deleting and modifying files.

There are obvious differences between DOM and SAX parsing, and when to use DOM or SAX is very clear.


dom4j

Dom4j is a very good Java XML API with excellent performance, powerful functions and easy to use.

Why Dom4j is needed

  • Disadvantage of dom: Comparing memory consumption
  • Sax disadvantage: can only read XML files, can not modify, add, delete
  • Dom4j: Not only can it improve efficiency, but also can crud operation.

Because Dom4j is not Sun’s product, we need to import the development kit to develop dom4j.


Parser for getting Dom4j

  • Dom4j parsers are needed for adding, deleting and modifying XML documents.
// Get the parser
        SAXReader saxReader = new SAXReader();

        // Getting Stream Objects to XML Files
        InputStream inputStream = DOM4j.class.getClassLoader().getResourceAsStream("1.xml");

        // Reading XML files through parsers
        Document document = saxReader.read(inputStream);

Get the Document object

As we all know, Document represents an XML document. Usually, we start with Document objects to perform CRUD operations.

There are three ways to get a Document object:

(1) Read the XML file and get the document object (which is the most commonly used)

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

(2) Parse the text in the form of XML and get the document object.

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

(3) Actively create document objects.

Document document =DocumentHelper.createDocument();

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

CRUD’s important words:

Reading the data of the XML document is to get the root element through Document, and then get other nodes through the root element, so as to operate!

If the structure of XML has multiple layers, it needs to be acquired layer by layer!

query

@Test
    public void read() throws DocumentException {

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

        // Getting Stream Objects to XML Files
        InputStream inputStream = dom4j11.class.getClassLoader().getResourceAsStream("1.xml");
   
        // Reading XML files through parsers
        Document document = saxReader.read(inputStream);

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

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

        // Get the name node, you can get the attribute or text content of the name node!
        String text = name.getText();

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

        System.out.println ("Text content:"+text);
        System.out.println ("Attribute content:"+attribute);
        
    }
  • The XML file is as follows:

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

  • Effect:

XML is that simple

  • Multi-tier queries:
// 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);
  • XML files and results:

XML is that simple


increase

In DOM4j, the DOM tree in memory should be written to the hard disk file, and the support of the converter is also needed!

Dom4j provides XMLWriter for us to update XML documents. Generally, when we create XMLWriter, we give two parameters, one is Writer, the other is OutputFormat.

XML is that simple

What’s the use of this Output Format? actuallyThat is to specify the format and encoding format of write-back XML。 Careful friends will find that we’re under jaxpThere is no format for updating the DOM tree in memory to the file hard disk using the Transformer class parsed by dom.! If you don’t believe it, go back and have a look!This Output Format allows us to update XML documents in a format as well.

// Create formatted objects
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();

        // Set the encoding, the default encoding is gb2312, read and write the encoding is inconsistent, will lead to scrambling!
        outputFormat.setEncoding("UTF-8");

        // Creating XMLWriter Objects
        XMLWriter xmlWriter = new XMLWriter(new FileWriter("2.xml"), outputFormat);

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

        // Closing flow
        xmlWriter.close();
  • Here we areCreate a new name node under the person node. The complete code is as follows:
@Test
    public void add() throws Exception {

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

        // Getting Stream Objects to XML Files
        InputStream inputStream = dom4j11.class.getClassLoader().getResourceAsStream("1.xml");

        // Reading XML files through parsers
        Document document = saxReader.read(inputStream);

        // Create a new node to set 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 under the root node
        root.add(newElement);

        // Create formatted objects
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();

        // Set the encoding, the default encoding is gb2312, read and write the encoding is inconsistent, will lead to scrambling!
        outputFormat.setEncoding("UTF-8");

        // Creating XMLWriter Objects
        XMLWriter xmlWriter = new XMLWriter(new FileWriter("2.xml"), outputFormat);

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

        // Closing flow
        xmlWriter.close();


    }
  • The effect is as follows. It’s formatted.

XML is that simple


Add nodes at specified locations! Now I want to add nodes before the age attribute!

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

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

        // Adds a node to a specified location
        list.add(1, element);
  • Design sketch:

XML is that simple



modify

  • I won’t post the XMLWriter and the code to get the Document object, it’s the same anyway!
// Get the age element
        Element age = document.getRootElement().element("age");
        age.setText("9999");
  • The results are as follows:

XML is that simple


delete

  • I won’t post the XMLWriter and the code to get the Document object, it’s the same anyway!
// Get the age node
        Element age = document.getRootElement().element("age");

        // Get the parent node of the age node, and delete the age node using the remove of the parent node!
        age.getParent().remove(age);
  • Effect:

XML is that simple


XPATH

What is XPATH

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

Why do we need XPATH

When we use Dom4j above,To get a node, we start with the root node and look down layer by layer, which is a little troublesome.

If we use XPATH, it’s very convenient to get nodes that get XML.


quick get start

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

  • XPATH documents are very international, even Chinese.

XML is that simple

  • XPATH document has a lot of examples, very good to learn, look at it, you know!

XML is that simple

  • Let’s use XPATH technology to read the information of the XML document. The XML document is as follows:

XML is that simple

  • Before that, we first got the root node, then the Guangdong node, and then the Guangzhou node. Then we can read the Tianhe node or the Luogang node. Let’s take a look at it.How convenient to use XPATH
// Get directly to the Luogang node
        org.dom4j.Node node =  document.selectSingleNode("//luogang");

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

        System.out.println(value);
  • Effect:

XML is that simple

Get what type of node, XPATH string should match, look up the document to know, here is no longer a repetition.


If there are any mistakes in the article, you are welcome to make corrections and communicate with each other. Students who are used to reading technical articles in Wechat can pay attention to Wechat Public Number: Java3y

Recommended Today

Sharing 10 useful methods of laravel 5.8 sets

This article is forwarded from the professional laravel developer community, original link: https://learnku.com/laravel/t… In laravel, there is a very useful class for manipulating arrays, called collections. I believe that every developer of laravel has used the collection more or less, especially when operating eloquent. In this article, I will list 10 common methods. 1. Weight […]