Leer archivo .XML java
DOM especificamente dom.Document, dom.Element, dom.Node y dom.NodeList.
Pasos.
Importar librerías.
import java.io.File;
import java.util.ArrayList;//this is optional
import javax.xml.parsers.DocumentBuilder;//important
import javax.xml.parsers.DocumentBuilderFactory;//important
import javax.xml.parsers.ParserConfigurationException;//optional but useful
import org.w3c.dom.Document;//important
import org.w3c.dom.Element;//important
import org.w3c.dom.Node;//important
import org.w3c.dom.NodeList;//important
import org.xml.sax.SAXException;//optional
Es probable que las librerías w3c no las
reconozca nuestro IDE, las podemos importar desde repositorios
Método que obtiene el valor del nodo no
terminal.
public String getNodeValue(String tag, Element element) {
Node node = (Node)(element.getElementsByTagName(tag).item(0).getFirstChild());// get info
return node.getNodeValue();//makes the info a string
}
Método que obtiene la información de un nodo terminal.
public ArrayList<String> getSubNodes(String tag, String subTag, Element element) {
ArrayList<String> list = new ArrayList<String>();
NodeList nodes = element.getElementsByTagName(tag);
Node node = nodes.item(0);
if(node.getNodeType() == Node.ELEMENT_NODE){
Element elementAux = (Element)(node);
NodeList matchList = elementAux.getElementsByTagName(subTag);
for (int i = 0; i < matchList.getLength(); i++) {
Node node2 = (Node)(matchList.item(i).getFirstChild());
list.add(node2.getNodeValue());
}
}
return list;
}
XML de prueba.
<hospital>
<admin>
<NOMBRE>Daniel</NOMBRE>
<APELLIDO>Bautista</APELLIDO>
<HORARIO>
<ENTRADA>14:00:00</ENTRADA>
<SALIDA>22:00:00</SALIDA>
</HORARIO>
</admin>
<admin>
<NOMBRE>Ana</NOMBRE>
<APELLIDO>Orozco</APELLIDO>
<HORARIO>
<ENTRADA>19:00:00</ENTRADA>
<SALIDA>04:00:00</SALIDA>
</HORARIO>
</admin>
<admin>
<NOMBRE>André</NOMBRE>
<APELLIDO>Apellido1</APELLIDO>
<HORARIO>
<ENTRADA>09:00:00</ENTRADA>
<SALIDA>11:00:00</SALIDA>
<ENTRADA>02:00:00</ENTRADA>
<SALIDA>06:00:00</SALIDA>
</HORARIO>
</admin>
<doctor>
<NOMBRE>André</NOMBRE>
<APELLIDO>Apellido1</APELLIDO>
<HORARIO>
<ENTRADA>09:00:00</ENTRADA>
<SALIDA>11:00:00</SALIDA>
</HORARIO>
</doctor>
</hospital>
Descarga el código presionando aquí.
Espero haberte ayudado :D
Comentarios
Publicar un comentario