import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class DOMExample {
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("example.xml"));
Element rootElement = document.getDocumentElement();
NodeList nodeList = rootElement.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Element Name: " + element.getNodeName());
System.out.println("Attribute Name: " + element.getAttribute("attributeName"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
public class SAXExample {
public static void main(String[] args) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean elementFlag = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("elementName")) {
elementFlag = true;
String attributeName = attributes.getValue("attributeName");
System.out.println("Element Name: " + qName);
System.out.println("Attribute Name: " + attributeName);
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("elementName")) {
elementFlag = false;
}
}
};
saxParser.parse(new File("example.xml"), handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.File;
public class JAXBExample {
public static void main(String[] args) {
try {
JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Employee employee = new Employee();
employee.setId(1);
employee.setName("John Doe");
employee.setDepartment("IT");
marshaller.marshal(employee, new File("employee.xml"));
} catch (Exception e) {
e.printStackTrace();
}
}
}