[英]Error getting attribute from xml with java parser
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 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 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. 我的问题是:我无法从xml文件读取属性“ anyo”。 If I remove "anyo" from libro.java and from getLibro the program runs fine. 如果我从libro.java和getLibro中删除“ anyo”,则程序运行正常。 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. anyo
属性属于titulo
元素。 In the code, you are getting its value from the libro
node instead. 在代码中,您将从libro
节点获取其值。
Simply call getAttribute
on the element that represents titulo
(the same way you're getting the node via the method getTextValue
): 只需在表示titulo
的元素上调用getAttribute
(与通过getTextValue
方法获取节点的方式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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.