El siguiente programa es un ejemplo muy sencillo de como utilizar un cursor para recorrer un documento XMLPartiendo
del documento XML books.xml
, listamos los títulos de los libros.
books.xml
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
//El programa java que recorre el documento para extraer los titulos y el atributo lang es el siguiente
public class ListaLibros {
public static void main(String[] args) throws FileNotFoundException, XMLStreamException {
// Creamos el flujo
XMLInputFactory xmlif = XMLInputFactory.newInstance();
XMLStreamReader xmlsr = xmlif.createXMLStreamReader(new FileReader("books.xml"));
String tag = null;
int eventType;
System.out.println("Lista de libros");
// iteramos con el cursor a lo largo del documento
while (xmlsr.hasNext()) {
eventType = xmlsr.next();
switch (eventType) {
case XMLEvent.START_ELEMENT:
tag = xmlsr.getLocalName();
if (tag.equals("title")) {
System.out.println(xmlsr.getElementText() + " idioma " + xmlsr.getAttributeValue(0));
}
break;
case XMLEvent.END_DOCUMENT:
System.out.println("Fin del documento");
break;
}
}
}
}