I have the following code:
Libreria.java
package libreriaparser;
public class Libreria {
public static void main(String[] args) {
Parser parser=new Parser();
parser.parseFicheroXml("biblioteca.xml");
parser.parseDocument();
parser.print();
}
}
Libro.java
package libreriaparser;
import java.io.Serializable;
//Defino el objeto tipo libro que contiene título, autor, año, editor y número de páginas.
public class Libro implements Serializable {
private String titulo=null;
private String autor=null;
private int anyo=0;
private String editor=null;
private int paginas=0;
//Incluyo dos contructores y los métodos get y set necesarios
public Libro() {
}
public Libro(String t, String a, int y, String e, int j) {
titulo = t;
autor = a;
anyo = y;
editor = e;
paginas = j;
}
public String getTitulo() {
return titulo;
}
public String getAutor() {
return autor;
}
public int getAnyo() {
return anyo;
}
public String getEditor() {
return editor;
}
public int getPaginas() {
return paginas;
}
public void setTitulo(String t) {
titulo = t;
}
public void setAutor(String a) {
autor = a;
}
public void setAnyo(short an) {
anyo = an;
}
public void setEditor(String e) {
editor = e;
}
public void setPaginas(short p) {
paginas = p;
}
//Defino un método print para mostrar los libros por consola
public void print(){
System.out.println("Título: "+titulo+". Autor: "+autor+". Editor: "+editor+". Número de páginas: "+paginas);
}
}
Parser.java
package libreriaparser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Parser {
private Document dom = null;
private ArrayList<Libro> libros = null;
public Parser() {
libros = new ArrayList<Libro>();
}
public void parseFicheroXml(String fichero) {
// creamos una factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// Creamos un documentbuilder
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
// parseamos el XML y obtenemos una representación DOM
dom = db.parse(fichero);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (SAXException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void parseDocument() {
// obtenemos el elemento raíz
Element docEle = dom.getDocumentElement();
// obtenemos el nodelist de elementos
NodeList nl = docEle.getElementsByTagName("libro");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
// obtenemos un elemento de la lista (libro)
Element el = (Element) nl.item(i);
// obtenemos un libro
Libro l1 = getLibro(el);
// lo añadimos al array
libros.add(l1);
}
}
}
private Libro getLibro(Element libroEle){
//para cada elemento libro, obtenemos su título, autor, año, editor y páginas
String titulo = getTextValue(libroEle,"titulo");
String autor = getTextValue(libroEle,"autor");
// Leemos el atributo año que va metido dentro del título del libro
String anyoString = libroEle.getAttribute("anyo");
int anyo = Integer.parseInt(anyoString);
String editor = getTextValue(libroEle,"editor");
int paginas = getIntValue(libroEle,"paginas");
//Creamos un nuevo libro con los elementos leídos del nodo
Libro l2 = new Libro(titulo, autor, anyo, editor, paginas);
return l2;
}
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
private int getIntValue(Element ele, String tagName) {
return Integer.parseInt(getTextValue(ele,tagName));
}
public void print(){
Iterator it = libros.iterator();
while(it.hasNext()) {
Libro l3=(Libro) it.next();
l3.print();
}
}
}
Biblioteca.xml
<?xml version="1.0" encoding="UTF-8"?>
<biblioteca>
<libro>
<titulo anyo="2008">Introduction to Linux</titulo>
<autor>Machtelt & Garrels</autor>
<editor>O'Reilly</editor>
<paginas>256</paginas>
</libro>
<libro>
<titulo anyo="1991">El lenguaje de programación C</titulo>
<autor>Kernighan & Ritchie</autor>
<editor>Prentice Hall</editor>
<paginas>294</paginas>
</libro>
</biblioteca>
My problem is: I can't read the attribute "anyo" from the xml file. If I remove "anyo" from libro.java and from getLibro the program runs fine. But I need to read this attribute. This is a job for my school and I don't know what I'm doing wrong. Thanks.
The anyo
attribute belongs to the titulo
element. In the code, you are getting its value from the libro
node instead.
Simply call getAttribute
on the element that represents titulo
(the same way you're getting the node via the method getTextValue
):
String anyoString = "0";
NodeList nl = libroEle.getElementsByTagName("titulo");
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
anyoString = el.getAttribute("anyo");
}
int anyo = Integer.parseInt(anyoString);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.