XML stands for "Extensible Markup Language". It has several advantages over other ways of storing information:
- It is extensible: After being designed and put into production, it is possible to extend XML by adding new tags so that it can continue to be used without any complications.
- The parser is a standard component; it is not necessary to create a specific parser for each version of the XML language. This enables the use of any available parser. In this way, bugs are avoided and application development is accelerated.
- If a third party decides to use a document created in XML, its structure is easy to understand and process. It improves compatibility between applications. We can connect applications from different platforms regardless of the data source; for instance, we could have an application on Linux with a Postgres database and communicate with another application on Windows with an MS-SQL Server database.
- We transform data into information, as concrete meaning is added and associated with a context, providing flexibility to structure documents.
SAX Reading
public class LecturaXMLSAX {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
File stocks = new File("stocks.xml");
DefaultHandler handler = new DefaultHandler() {
boolean bSimbol = false;
boolean bPreu = false;
boolean bQuantitat = false;
@Override
public void startElement(String uri, String nomLocal, String nomElement,Attributes atributs) throws SAXException {
System.out.println("Inici d'element :" + nomElement);
if (nomElement.equalsIgnoreCase("simbol")) {
bSimbol = true;
}
if (nomElement.equalsIgnoreCase("preu")) {
bPreu = true;
}
if (nomElement.equalsIgnoreCase("quantitat")) {
bQuantitat = true;
}
}
@Override
public void endElement(String uri, String localName,
String nomElement) throws SAXException {
System.out.println("Final d'element :" + nomElement);
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (bSimbol) {
System.out.println("Simbol: " + new String(ch, start, length));
bSimbol = false;
}
if (bPreu) {
System.out.println("Preu: " + new String(ch, start, length));
bPreu = false;
}
if (bQuantitat) {
System.out.println("Quantitat: " + new String(ch, start, length));
bQuantitat = false;
}
}
};
saxParser.parse(stocks, handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In SAX, events are triggered as the XML is being parsed. When the parser parses the XML and encounters a start tag, it triggers the startElement event. Similarly, when the end of the tag is reached, endElement is triggered. Using a SAX parser implies that we need to handle these events and make sense of the data obtained with each event.
XML Reading by Nodes (DOM)
public class LecturaXMLDOM {
public static void main(String args[]) {
try {
File stocks = new File("stocks.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(stocks);
doc.getDocumentElement().normalize();
System.out.println("raiz " + doc.getDocumentElement().getNodeName());
NodeList nodes = doc.getElementsByTagName("stock");
System.out.println("==========================");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Stock símbolo: " + obtenerContenido("simbol", element));
System.out.println("Stock precio: " + obtenerContenido("preu", element));
System.out.println("Stock cantidad: " + obtenerContenido("quantitat", element));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static String obtenerContenido(String etiqueta, Element element) {
NodeList nodes = element.getElementsByTagName(etiqueta).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
In DOM, no events are triggered. The entire XML is parsed, and a DOM tree (of the XML nodes) is generated and returned. Once parsed, the user can navigate through the tree to access the different data previously embedded in the various XML nodes.
In general, DOM is easier to use, but it carries the overhead of parsing the entire XML before starting to use it.
Creating an XML Document
public class CreacioEscripturaXML {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document nodeDocument = docBuilder.newDocument();
Element elementArrel = nodeDocument.createElement("empresa");
nodeDocument.appendChild(elementArrel);
Element treballador = nodeDocument.createElement("treballador");
elementArrel.appendChild(treballador);
treballador.setAttribute("id", "1");
Element nom = nodeDocument.createElement("nom");
nom.appendChild(nodeDocument.createTextNode("sergi"));
treballador.appendChild(nom);
Element cognom = nodeDocument.createElement("cognom");
cognom.appendChild(nodeDocument.createTextNode("grau"));
treballador.appendChild(cognom);
Element sou = nodeDocument.createElement("salari");
sou.appendChild(nodeDocument.createTextNode("100000"));
treballador.appendChild(sou);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource origen = new DOMSource(nodeDocument);
StreamResult sortidaXML = new StreamResult(new File("empresa.xml"));
transformer.transform(origen, sortidaXML);
System.out.println("Desat!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}