Home >Java >javaTutorial >How to Read and Write XML Data in Java Using the DOM?

How to Read and Write XML Data in Java Using the DOM?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 01:26:09498browse

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:

  1. 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.*;
  2. Instantiate DocumentBuilderFactory: Create an instance of DocumentBuilderFactory, responsible for creating DocumentBuilder objects:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  3. Create DocumentBuilder: Use the factory to obtain a DocumentBuilder instance for parsing the XML document:

    DocumentBuilder db = dbf.newDocumentBuilder();
  4. 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);
  5. Access XML Elements: Utilize getElementsByTagName(tag) to retrieve nodes corresponding to the specified tag:

    NodeList nl = doc.getElementsByTagName(tag);
  6. 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:

  1. Initialize Document: Create a new Document instance:

    Document dom = db.newDocument();
  2. Create Root Element: Establish the root element of the XML document:

    Element rootElement = dom.createElement("rootElement");
  3. 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);
  4. Append Root Element to Document: Add the root element to the document:

    dom.appendChild(rootElement);
  5. Instantiate Transformer: Create a Transformer instance for transforming the DOM model into an XML document:

    Transformer tr = TransformerFactory.newInstance().newTransformer();
  6. 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");
  7. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn