XML: Extensible Markup Language -- similar to HTML, but not an alternative to HTML
- Purpose: transmit data instead of display data, self descriptive, no predefined (you need to define your own label)
- Features: XML has nothing to do with the development platform of operating system and programming language, and can realize data exchange between different systems
- Role: data interaction, configuring applications and websites, Ajax cornerstone
XML and HTML are designed for different purposes
- XML: storing and transferring data
- HTML: displaying data
XML parsing: DOM parsing, SAX parsing, JDOM parsing, DOM4J parsing
The first two parsing methods are the official basic methods, and the last two are extension methods, which need to import jar packages
- DOM parsing (Document Object Model): access XML file information through the object model
- Advantages: it forms a tree structure, which is helpful to understand and master, easy to write code and easy to modify
- Disadvantages: reading the file at one time consumes a lot of memory (if the XML file is too large, it will easily affect the parsing performance and cause memory overflow)
- SAX parsing (Simple APIS for XML): fast reading and writing XML data (sequential mode)
- When SAX analyzer analyzes an XML document, it will trigger a series of events and activate the corresponding event function to access the XML document; The SAX interface is also known as the event driven interface
- Advantages: the event driven mode is adopted, which consumes less memory and is suitable for processing only different data in XML files
- Disadvantages: coding is troublesome, and it is difficult to access multiple different data in XML files at the same time
- JDOM: Based on tree structure, only concrete classes are used, and interfaces are not used
- It is an open source project that uses pure Java to parse documents and generate serialization
- DOM4J: is an intelligent branch that combines many functions beyond the representation of basic XML documents, using interfaces and abstract basic class methods
- Excellent performance, good flexibility, powerful functionality and extremely easy to use. It is an open source file
DOM4J parsing
1. Create XML file
- Guide Package: dom4j-1.6.1
- Create a Document object (createDocument) -- add a root node / child node (addElement) -- add an attribute (addAttribute (attribute name, value)) -- add information (setText)
- Generate XML format (createPrettyPrint) -- set character encoding (setEncoding("UTF-8"))
- Generate XML file
import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class DemoA { public static void main(String[] args) { try { //1. Create a Document object Document document= DocumentHelper.createDocument(); // Add root node Element books = document.addElement("books"); // Add child nodes for the root node Element book1 = books.addElement("book "); //Add attributes to child nodes book1.addAttribute("id","bk101"); Element author = book1.addElement("author"); //Adding a value < author > value < / author > to a node author.setText("Wang Shan"); Element title = book1.addElement("title"); title.setText(".NET Advanced programming"); Element description = book1.addElement("description"); description.setText("contain C#Framework and network programming, etc.); // Add child nodes for the root node Element book2 = books.addElement("book "); //Add attributes to child nodes book2.addAttribute("id","bk102"); book2.addElement("author").setText("Ming Ming Li"); book2.addElement("title").setText("XML Basic programming"); book2.addElement("description").setText("contain XML Basic concepts and functions"); // Format the generated XML OutputFormat format = OutputFormat.createPrettyPrint(); //Set character encoding set & lt; <& gt; > & amp; & & apos; ' & quot; "<! [CDATA [special symbols]] > format.setEncoding("UTF-8"); File file = new File("D:\\java\\books.xml"); //Judge whether the file exists. If it does not exist, create a new file if(!file.exists()){ file.createNewFile(); } //Update the modified data to the document XMLWriter writer = new XMLWriter(new FileOutputStream(file),format); writer.write(document); writer.close(); System.out.println("XML File generation!"); } catch (IOException e) { e.printStackTrace(); } } }
Add information (setText) escape character:
Escape character | meaning |
---|---|
< ; | < |
> ; | > |
& ; | & |
&apos ; | ' |
" ; | " |
2. Read XML file
1. Child node traversal
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.File; import java.util.List; public class DemoB { public static void main(String[] args) { File file = new File("E:\\IDEA\\workspace\\java_t9\\doc\\FullChannels.xml"); if (file.exists()) { try { SAXReader reader = new SAXReader(); //Read file get Document interface Document document = reader.read(file); // Get root node Element root = document.getRootElement(); // Gets the child node under the root node List<Element> channel = root.elements(); for (Element e : channel) { List<Element> channelid=e.elements(); for (Element e2:channelid){ switch(e2.getName()) { case "channelType": System.out.println("Channel type:" +e2.getText()); break; case "tvChannel": System.out.println("Channel name:" +e2.getText()); break; case "path": System.out.println("Channel local path:" +e2.getText()); break; } } } } catch (DocumentException e) { e.printStackTrace(); } } } }
2. Obtain child nodes by parent and child node names
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.File; import java.util.List; public class DemoQuery { public static void main(String[] args) { File file = new File("E:\\IDEA\\workspace\\java_t9\\doc\\FullChannels.xml"); if (file.exists()) { try { SAXReader reader = new SAXReader(); Document document = reader.read(file);//Read fullchannels XML file Element root = document.getRootElement();//Get root node TVChannel List<Element> channel = root.elements();//Get all next child nodes (objects) for (Element e : channel) { System.out.println("Channel type:" + e.elementText("channelType")); System.out.println("Channel name:" + e.elementText("tvChannel")); System.out.println("Channel local path:" + e.elementText("path")); } catch (DocumentException e) { e.printStackTrace(); } } } }
3. Get attribute and name
//Get current node name System.out.println(bookElem.getName()); //Get current node properties System.out.println(bookElem.attributeValue("id"));
3. Modify XML file
1. Modify: modify the contents of child nodes and parent nodes element("node name") setText ("modified content") / child node setText ("modified content")
2. Delete: remove the child node e1, e.remove(e1) from the parent node E;
3. Add: add the child node playTime at the parent node X and add the content, x.addElement("playTime") setText(“2021-9-29 04:25”);
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import java.io.*; import java.util.List; public class DemoChange { public static void main(String[] args) { File file=new File("E:\\IDEA\\workspace\\java_t9\\doc\\Phoenix Satellite TV.xml"); if(file.exists()){ try { SAXReader reader=new SAXReader(); Document document =reader.read(file); Element root=document.getRootElement(); List<Element> programList= root.elements(); for (Element e:programList) { List<Element> progream=e.elements(); for(Element e1:progream){ Element playTime=e1.element("playTime"); Element name=e1.element("name"); Element path=e1.element("path"); //delete if(name.getText().trim().equals("I read newspapers every day(28/09/09)") && playTime.getText().equals("2013-9-29 02:15")){ e.remove(e1);//Remove child node from parent node } //Modify trim() -- delete the influence of spaces if(name.getText().trim().equals("Music Chinese style(442)") && playTime.getText().equals("2013-9-29 04:25")) { path.setText("C:\\music\\"); } } //add to //Create a Document object and build a Document structure Element x=e.addElement("Progream"); x.addElement("playTime").setText("2021-9-29 04:25"); x.addElement("name").setText("Music Chinese style(442)"); x.addElement("path").setText("**"); } XMLWriter output = new XMLWriter(new FileOutputStream(file)); output.write(document); output.close(); } catch (DocumentException e) { e.printStackTrace(); } //Prevent FileOutputStream errors catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }