Home >Java >javaTutorial >How to Read and Write XML Data in Java Using the DOM?
How to Access and Modify XML Data with Java
The Document Object Model (DOM) provides a standard interface for accessing and editing XML documents in Java. Here's a detailed guide on how to read and write XML files using DOM:
Reading XML Files:
Import Libraries: Begin by importing the necessary XML-related libraries:
import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.xml.sax.*; import org.w3c.dom.*;
Instantiate DocumentBuilderFactory: Create an instance of DocumentBuilderFactory, responsible for creating DocumentBuilder objects:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Create DocumentBuilder: Use the factory to obtain a DocumentBuilder instance for parsing the XML document:
DocumentBuilder db = dbf.newDocumentBuilder();
Parse XML Document: Invoke parse() on the builder to parse the XML file and create a DOM model of the document:
Document dom = db.parse(xmlFile);
Access XML Elements: Utilize getElementsByTagName(tag) to retrieve nodes corresponding to the specified tag:
NodeList nl = doc.getElementsByTagName(tag);
Extract Text Value: If the node has child nodes, use getFirstChild().getNodeValue() to retrieve the text value:
String value = nl.item(0).getFirstChild().getNodeValue();
Writing XML Files:
Initialize Document: Create a new Document instance:
Document dom = db.newDocument();
Create Root Element: Establish the root element of the XML document:
Element rootElement = dom.createElement("rootElement");
Add Child Elements: Append child elements to the root element and provide their text content:
Element childElement = dom.createElement("childElement"); childElement.appendChild(dom.createTextNode("text content")); rootElement.appendChild(childElement);
Append Root Element to Document: Add the root element to the document:
dom.appendChild(rootElement);
Instantiate Transformer: Create a Transformer instance for transforming the DOM model into an XML document:
Transformer tr = TransformerFactory.newInstance().newTransformer();
Set Transformer Properties: Configure the transformer to indent the XML and use proper encoding:
tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
Transform and Save XML: Pass the DOM source to the transformer and specify the destination file for saving as XML:
tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile)));
The above is the detailed content of How to Read and Write XML Data in Java Using the DOM?. For more information, please follow other related articles on the PHP Chinese website!