Middle
What methods of XML writing do you know?
sobes.tech AI
Answer from AI
XML can be written in several ways, depending on the required level of control and document complexity:
- DOM (Document Object Model): Loads the entire XML into memory as a tree of objects, allowing navigation and modifications.
- SAX (Simple API for XML): Parses the file event-driven, calling handlers upon detecting start/end tags, text, etc. Suitable for large files.
- StAX (Streaming API for XML): A combination of SAX and DOM, allows incremental parsing with more control than SAX.
- JAXB (Java Architecture for XML Binding): Enables automatic conversion between Java objects and XML using annotations.
Example of creating XML using DOM:
// Example of creating XML using DOM
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class CreateXmlDom {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
// root element
Element rootElement = doc.createElement("cars");
doc.appendChild(rootElement);
// car element
Element car = doc.createElement("car");
rootElement.appendChild(car);
// model element
Element model = doc.createElement("model");
model.appendChild(doc.createTextNode("BMW"));
car.appendChild(model);
// year element
Element year = doc.createElement("year");
year.appendChild(doc.createTextNode("2022"));
car.appendChild(year);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new java.io.File("cars.xml"));
transformer.transform(source, result);
System.out.println("File saved!");
}
}
Example of creating XML using JAXB:
// Example of creating XML using JAXB
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
import java.io.*;
@XmlRootElement
public class Car {
@XmlElement
public String model;
@XmlElement
public int year;
// Getters and Setters
public String getModel() { return model; }
public void setModel(String model) { this.model = model; }
public int getYear() { return year; }
public void setYear(int year) { this.year = year; }
public static void main(String[] args)throws Exception {
Car car = new Car();
car.setModel("Audi");
car.setYear(2023);
JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(car, System.out);
jaxbMarshaller.marshal(car, new File("car.xml"));
}
}