XML Processing (DOM and SAX)

XML (eXtensible Markup Language) processing in Java involves parsing and manipulating XML documents using different APIs such as DOM (Document Object Model) and SAX (Simple API for XML). DOM provides a tree-based representation of the XML document in memory, allowing easy traversal and modification, while SAX is an event-driven API that parses XML documents sequentially and triggers events as it encounters elements, attributes, and other XML constructs. Here's how you can perform XML processing using DOM and SAX in Java:


XML Processing with DOM

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomExample {

    public static void main(String[] args) {
        try {
            // Create DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            // Create DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Parse XML file
            Document doc = builder.parse("data.xml");

            // Get root element
            Element root = doc.getDocumentElement();

            // Traverse XML tree
            NodeList nodeList = root.getElementsByTagName("book");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    String title = element.getElementsByTagName("title").item(0).getTextContent();
                    String author = element.getElementsByTagName("author").item(0).getTextContent();
                    System.out.println("Title: " + title + ", Author: " + author);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


XML Processing with SAX

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 {
            // Create SAXParserFactory
            SAXParserFactory factory = SAXParserFactory.newInstance();

            // Create SAXParser
            SAXParser parser = factory.newSAXParser();

            // Parse XML file
            File file = new File("data.xml");
            parser.parse(file, new MyHandler());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class MyHandler extends DefaultHandler {
        boolean bTitle = false;
        boolean bAuthor = false;

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if (qName.equalsIgnoreCase("title")) {
                bTitle = true;
            } else if (qName.equalsIgnoreCase("author")) {
                bAuthor = true;
            }
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if (bTitle) {
                System.out.println("Title: " + new String(ch, start, length));
                bTitle = false;
            } else if (bAuthor) {
                System.out.println("Author: " + new String(ch, start, length));
                bAuthor = false;
            }
        }
    }
}


Conclusion

XML processing in Java can be performed using DOM or SAX APIs. DOM provides a tree-based representation of XML documents, allowing easy traversal and modification, while SAX is an event-driven API that parses XML documents sequentially. Depending on your requirements and preferences, you can choose the appropriate XML processing approach for your Java applications.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....