Parse XML in Java: DOM, SAX, JAXB

XML files in Java are not executed directly, but instead they are read and parsed using Java code. Common methods include using APIs such as DOM, SAX, or JAXB to manipulate XML files.

  1. Using DOM: DOM (Document Object Model) is an API based on a tree structure, which loads the entire XML document into memory and allows for manipulating the XML file through nodes. Parsing XML files with DOM requires loading the file into memory first, and then traversing and manipulating it through nodes.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("file.xml"));

Element root = document.getDocumentElement();
NodeList nodeList = root.getElementsByTagName("tag");
for(int i=0; i<nodeList.getLength(); i++){
    Node node = nodeList.item(i);
    //处理节点操作
}
  1. Using SAX: SAX (Simple API for XML) is an event-based API that parses XML files in a way that is driven by events. As the parser reads the XML file, it triggers corresponding events that developers can implement logic to handle.
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler(){
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        //处理开始标签事件
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        //处理元素内容事件
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        //处理结束标签事件
    }
};
parser.parse(new File("file.xml"), handler);
  1. JAXB, which stands for Java Architecture for XML Binding, is a part of the Java EE platform that allows for mapping between Java objects and XML documents. With JAXB, data from XML files can be mapped to Java objects and vice versa.
JAXBContext context = JAXBContext.newInstance(Class.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Class obj = (Class) unmarshaller.unmarshal(new File("file.xml"));

With the above methods, it is possible to manipulate XML files in Java, read the data within them, and perform the appropriate processing.

bannerAds