1. DOM principle: XML's "Clone War"
Imagine you want to copy the entire Disneyland:
Full loading technique: swallow the entire XML file into memory and turn it into a node tree (like converting castle drawings into 3D models)
Random access privilege: can teleport to any corner at any time: "I want to modify the color of the third brick!" (and SAX can only see the end from the beginning)
Modify super power: support adding, deleting, modifying and checking, and transforming the XML world at will like playing "The Sims"
2. Practical drill: Use DOM to build a "programmer theme park"
Project blueprint (programmer_park.xml):
<Theme park name="996 Happy Valley"> <area type="Code Abyss" geohash="wx4g0b1"> <facility > <name>Unlimited coffee shop</name> <Danger level>★★★★☆</Danger level> </facility> <facility > <name>Changes in demand roller coaster</name> <Danger level>★★★★★</Danger level> </facility> </area> </Theme park>
Architect Toolkit ()
import org..*; import .*; import .*; import ; import ; public class DomArchitect { public static void main(String[] args) throws Exception { // Load the entire park to memory DocumentBuilderFactory factory = (); DocumentBuilder builder = (); Document park = ("programmer_park.xml"); // Print all hazardous facilities NodeList rides = ("facility"); ("⚠️ High-risk Facilities List:"); for (int i=0; i<(); i++) { Element ride = (Element) (i); String name = ("name").item(0).getTextContent(); String level = ("Hazard level").item(0).getTextContent(); (name + " | Danger Index:" + level); } // Add a deadly facility Element newRide = ("facility"); ("id", "3"); Element name = ("name"); (("Deadline Bungee Table")); Element level = ("Hazard level"); (("★★★★★★")); // Break through five stars! (name); (level); ().getFirstChild().appendChild(newRide); // Save the modified paradise (beware of memory leaks!) Transformer transformer = ().newTransformer(); (new DOMSource(park), new StreamResult("programmer_park_modified.xml")); } }
Running results:
⚠️ High-risk facilities list:
Unlimited coffee shop | Danger index: ★★★★☆
Demand Change Roller Coaster | Hazard Index: ★★★★★
(The generated new XML will have an additional "Deadline bungee" and the danger index will break through the sky!)
3. DOM vs SAX: The Peak Showdown between Architect and Detective
DOM Architect | SAX Detective | |
---|---|---|
Memory consumption | Need to move to the entire building materials market (full loading) | Only bring detective toolkit (streaming) |
Operation method | Walls can be demolished at will (randomly modified) | Only do live records (read-only) |
Response speed | Transport materials before decoration (initialization is slow) | Start work immediately when you arrive at the site (quick start) |
Applicable scenarios | Exquisite villas that need to be restructured | Quickly search the huge warehouse for crime scene |
4. Three "sexy operations" of DOM operations
Lightning positioning
Use XPath to airdrop directly to the specified node, such as using a portal:
XPath xpath = ().newXPath(); Node node = (Node) ("//Facilities [name='Demand Change Roller Coaster']", park, );
2. Attribute Invisibility
Dynamically modify the geohash coordinates to allow the facility to "move instantly":
Element area = (Element) ("area").item(0); ("geohash", "wx4g0b9"); // Teleport from the abyss to the toilet
3. Node cloning method
Copy the roller coaster and rename it, saving time and effort:
Node clonedRide = (1).cloneNode(true); ((Element)clonedRide).setAttribute("id", "4"); ().item(0).setTextContent("Demand Resurrection Roller Coaster");
5. The fatal trap of DOM
1. Memory black hole
Load 1GB of XML file ≈ Build an aircraft carrier in memory (beware of OOM air raids!)
2. Blank nodes hit the wall
Line breaks in XML will be regarded as Text nodes, and it may be trapped during traversal:
// Error demonstration: The first child node can be a blank text node directly!// Element name = (Element) (); // Correct posture: Filter text nodesNodeList children = (); for (int i=0; i<(); i++) { if ((i).getNodeType() == Node.ELEMENT_NODE) { Element child = (Element) (i); // Handle real nodes } }
3. Thread safety shock
Document objects are not thread-safe! Multiple threads are renovating at the same time and will tear down your LEGO Castle.
6. DOM philosophy: Memory is the world
Each Element node is a LEGO building block
Each Text node is a sticker on the building blocks
Every Attribute is a snap-on design for building blocks
This is the end of this article about Java's study guide to parsing XML using DOM. For more related Java DOM parsing XML content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!