Foros del Web » Programación para mayores de 30 ;) » Java »

Leer XML varios bucles.

Estas en el tema de Leer XML varios bucles. en el foro de Java en Foros del Web. Hola, envio este mensaje por que estoy intentando leer un XML des de una clase de Java. La vez anterior me funcionó correctamente ya que ...
  #1 (permalink)  
Antiguo 29/03/2015, 10:41
Avatar de veniwarez  
Fecha de Ingreso: julio-2010
Mensajes: 110
Antigüedad: 13 años, 9 meses
Puntos: 3
Leer XML varios bucles.

Hola, envio este mensaje por que estoy intentando leer un XML des de una clase de Java.
La vez anterior me funcionó correctamente ya que era una ciudad que guardaba diferentes dias. El problema ahora es que tengo diferentes ciudades y consigo hacer un bucle para leer cada ciudad entonces intento leer cada dia guardado de cada ciudad pero no funciona, solo me lee un dia por cada ciudad.

Tienen alguna sugerencia.

Atte VW
  #2 (permalink)  
Antiguo 29/03/2015, 11:01
Avatar de Profesor_Falken  
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Leer XML varios bucles.

Buenas,

Con la información que das sólo podemos hacer esto:



Que leas ciudades, libros o tipos de quesos no nos aporta ninguna pista sobre lo que estás haciendo.

Que estás utilizando para leer el XML? DOM, JAX, stax? Quizás una librería específica (JDOM, DOM4J...)?

Para poder ayudate necesitamos al menos un ejemplo del XML que intentas leer y el código que has desarrollado.


Un saludo
__________________
If to err is human, then programmers are the most human of us
  #3 (permalink)  
Antiguo 29/03/2015, 11:12
Avatar de veniwarez  
Fecha de Ingreso: julio-2010
Mensajes: 110
Antigüedad: 13 años, 9 meses
Puntos: 3
Respuesta: Leer XML varios bucles.

Mire el XML es como así:

<Ciutats>
<Ciutat>
<Nom>Torremolinos1</Nom>
<Provincia>Malaga</Provincia>
<Dades>
<Dada dia='2111-11-11'>
<TempMax>1.0</TempMax>
<TempMin>7.0</TempMin>
<TempAve>8.7</TempAve>
<VMax>8.0</VMax>
<VRatxa>28.0</VRatxa>
<Prec>29.8</Prec>
</Dada>
</Dades>
</Ciutat>
<Ciutat>
<Nom>Torremolinos2</Nom>
<Provincia>Malaga</Provincia>
<Dades>
<Dada dia='2111-01-14'>
<TempMax>2.0</TempMax>
<TempMin>7.0</TempMin>
<TempAve>8.7</TempAve>
<VMax>8.0</VMax>
<VRatxa>28.0</VRatxa>
<Prec>29.8</Prec>
</Dada>
</Dades>
</Ciutat>
<Ciutat>
<Nom>Torremolinos3</Nom>
<Provincia>Malaga</Provincia>
<Dades>
<Dada dia='2111-01-18'>
<TempMax>3.0</TempMax>
<TempMin>7.0</TempMin>
<TempAve>8.7</TempAve>
<VMax>8.0</VMax>
<VRatxa>28.0</VRatxa>
<Prec>29.8</Prec>
</Dada>
<Dada dia='2222-11-12'>
<TempMax>4.0</TempMax>
<TempMin>7.0</TempMin>
<TempAve>8.7</TempAve>
<VMax>8.0</VMax>
<VRatxa>28.0</VRatxa>
<Prec>29.8</Prec>
</Dada>
</Dades>
</Ciutat>
</Ciutats>



El problema de lo que uso para leerlo es que lo he sacado de un ejemplo que nos dio el profesor y que supe adaptar para leer una sola ciudad.

Su ejemplo era como así:


import java.io.File;
import java.io.IOException;

import javax.xml.parsers.*;

import org.apache.commons.cli.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

public class Main {

/**
* Run the examples of use org.apache.commons.cli for arguments and read XML
* file the construct the object {@link Lecturer}
* @param args -h | -f path/of/file.xml
* @throws ParseException
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
public static void main(String[] args) throws ParseException, IOException, ParserConfigurationException, SAXException {

String fileName = "xml/Data.xml";
/**
* Read XML file
*/
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File(fileName);
Document document = builder.parse(file);

// Return ed element of XML file.
Element ed = document.getDocumentElement();

// Return lecturer elements list
NodeList lecturerList = ed.getElementsByTagName("Lecturer");
if(lecturerList != null && lecturerList.getLength() > 0) {
for (int i=0; i<lecturerList.getLength(); i++){

//Get a lecturer
Element lecturer = (Element) lecturerList.item(i);

//Get lecturer's email attribute
String email = lecturer.getAttribute("email");

//Get lecturer's name label
String name = new String();
NodeList nameList = lecturer.getElementsByTagName("name");
if(nameList != null && nameList.getLength() > 0) {
Element nameElement = (Element)nameList.item(0);
name = nameElement.getFirstChild().getNodeValue();

}
//Get lecturer's surnames label
String surnames = new String();
NodeList surnamesList = lecturer.getElementsByTagName("surnames");
if(surnamesList != null && surnamesList.getLength() > 0) {
Element surnamesElement = (Element)surnamesList.item(0);
surnames = surnamesElement.getFirstChild().getNodeValue();

}
System.out.println(" LECTURER "+(i+1));
System.out.println("-------------");
System.out.println(" NAME: "+name+" "+surnames);
System.out.println(" EMAIL: "+email);
System.out.println(" ");

}
}
}

}



En el ejercicio anterior yo lo adapté para leer de una ciudad, su nombre, provincia, y entonces leía las temperaturas, los días, vientos.... Funcionó
  #4 (permalink)  
Antiguo 29/03/2015, 12:57
Avatar de veniwarez  
Fecha de Ingreso: julio-2010
Mensajes: 110
Antigüedad: 13 años, 9 meses
Puntos: 3
Respuesta: Leer XML varios bucles.

Esta es el mejor lector que he podido hacer hasta el momento ya que lee todas las ciudades y lo más importante, lee todos los días. El problema es que lee los días al final y como podemos comprobar en "nom"+name, los lee despues de haber leido las diferentes ciudades o sea ahora lee así C (Ciudad) D (Dia)>> C1,C2,C3,D1,D2,D3,D4,D5 cuando tendría que leer por ejemplo C1,D1,C2,D2,C3,D3,D4,D5.

Alguna idea para solucionar este problema?

Codigo:



import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.xml.parsers.*;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

public class main {

/**
* Run the examples of use org.apache.commons.cli for arguments and read XML
* file the construct the object {@link Lecturer}
* @param args -h | -f path/of/file.xml
* @throws ParseException
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
public static void main(String[] args) throws ParseException, IOException, ParserConfigurationException, SAXException {
inicialitzar();

}




public static void inicialitzar() throws ParseException, IOException, ParserConfigurationException, SAXException{
String fileName = "xml/dades2.xml";
/**
* Read XML file
*/
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File(fileName);
Document document = builder.parse(file);

// Return ed element of XML file.
Element ed = document.getDocumentElement();
String name="";
String province="";
// Return lecturer elements list
NodeList lecturerList = ed.getElementsByTagName("Ciutat");
if(lecturerList != null && lecturerList.getLength() > 0) {
for (int i=0; i<lecturerList.getLength(); i++){

//Get a lecturer
Element lecturer = (Element) lecturerList.item(i);

//Get lecturer's name label
name = new String();
NodeList nameList = lecturer.getElementsByTagName("Nom");
if(nameList != null && nameList.getLength() > 0) {
Element nameElement = (Element)nameList.item(0);
name = nameElement.getFirstChild().getNodeValue();

}
//Get lecturer's name label
province = new String();
NodeList provinceList = lecturer.getElementsByTagName("Provincia");
if(provinceList != null && provinceList.getLength() > 0) {
Element nameElement = (Element)provinceList.item(0);
province = nameElement.getFirstChild().getNodeValue();

}
//tco=new TempsCiutatOrdenat(name,province,maxim);
System.out.println("----------------------------------");

System.out.println(" CITY: "+name);

System.out.println(" PROVINCE: "+province);
System.out.println("----------------------------------");

}

String dia="";
float tempMax=0F;
float tempMin=0F;
float tempAve=0F;
float vMax=0F;
float vRatxa=0F;
float prec=0F;
NodeList lecturerList2 = ed.getElementsByTagName("Dada");
if(lecturerList2 != null && lecturerList2.getLength() > 0) {
for (int i2=0; i2<lecturerList2.getLength(); i2++){
Element lecturer2 = (Element) lecturerList2.item(i2);
dia = lecturer2.getAttribute("dia");
//Get a lecturer


//Get lecturer's name label
NodeList nameList = lecturer2.getElementsByTagName("TempMax");
if(nameList != null && nameList.getLength() > 0) {
Element nameElement = (Element)nameList.item(0);
tempMax = Float.parseFloat(nameElement.getFirstChild().getNo deValue());

}
//Get lecturer's name label

NodeList provinceList = lecturer2.getElementsByTagName("TempMin");
if(provinceList != null && provinceList.getLength() > 0) {
Element nameElement = (Element)provinceList.item(0);
tempMin = Float.parseFloat(nameElement.getFirstChild().getNo deValue());
}

provinceList = lecturer2.getElementsByTagName("TempAve");
if(provinceList != null && provinceList.getLength() > 0) {
Element nameElement = (Element)provinceList.item(0);
tempAve = Float.parseFloat(nameElement.getFirstChild().getNo deValue());
}

provinceList = lecturer2.getElementsByTagName("VMax");
if(provinceList != null && provinceList.getLength() > 0) {
Element nameElement = (Element)provinceList.item(0);
vMax = Float.parseFloat(nameElement.getFirstChild().getNo deValue());
}

provinceList = lecturer2.getElementsByTagName("VRatxa");
if(provinceList != null && provinceList.getLength() > 0) {
Element nameElement = (Element)provinceList.item(0);
vRatxa = Float.parseFloat(nameElement.getFirstChild().getNo deValue());
}

provinceList = lecturer2.getElementsByTagName("Prec");
if(provinceList != null && provinceList.getLength() > 0) {
Element nameElement = (Element)provinceList.item(0);
prec = Float.parseFloat(nameElement.getFirstChild().getNo deValue());
}
DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd");
Date data1 = d1.parse(dia);
//tco.afegirTempsDia(data1, tempMax, tempMin, tempAve, vMax, vRatxa, prec);

System.out.println("**************************");
System.out.println(" DIA: "+dia+" nom"+name);
System.out.println(" TEMP MAX:"+tempMax);
System.out.println(" TEMP MIN:"+tempMin);
System.out.println(" TEMP AVE:"+tempAve);
System.out.println(" TEMP VMAX:"+vMax);
System.out.println(" TEMP VRATXA:"+vRatxa);
System.out.println(" TEMP PREC:"+prec);

}



}
}
}

}

Última edición por veniwarez; 29/03/2015 a las 13:13
  #5 (permalink)  
Antiguo 29/03/2015, 14:04
Avatar de veniwarez  
Fecha de Ingreso: julio-2010
Mensajes: 110
Antigüedad: 13 años, 9 meses
Puntos: 3
Respuesta: Leer XML varios bucles.

Dejo un ejemplo del output de la ejecución actual:

----------------------------------
CITY: Torremolinos1
PROVINCE: Malaga
----------------------------------
**************************
DIA: 2111-11-11 nomTorremolinos1
TEMP MAX:1.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8

----------------------------------
CITY: Torremolinos2
PROVINCE: Malaga
----------------------------------
**************************
DIA: 2111-01-14 nomTorremolinos2
TEMP MAX:2.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8
----------------------------------
CITY: Torremolinos3
PROVINCE: Malaga
----------------------------------
**************************
DIA: 2111-01-18 nomTorremolinos3
TEMP MAX:3.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8
**************************
DIA: 2222-11-12 nomTorremolinos3
TEMP MAX:4.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8
  #6 (permalink)  
Antiguo 30/03/2015, 05:09
Avatar de Profesor_Falken  
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Leer XML varios bucles.

Cita:
hora lee así C (Ciudad) D (Dia)>> C1,C2,C3,D1,D2,D3,D4,D5 cuando tendría que leer por ejemplo C1,D1,C2,D2,C3,D3,D4,D5.
En la salida que has puesto parece correcta y de acuerdo con lo que comentas. Que es lo que esta mal entonces?

Podrias poner un ejemplo de la salida que da y de la que esperas?

Nota: por favor, intenta utilizar la herramienta "Highlight" cuando pones codigo en el post. Resulta ilegible si no lo haces.

Nota2: creo que me has escrito un mensaje privado. Lo he borrado inmediatamente sin siquiera leerlo como siempre hago con todos los privados. Podemos comunicarnos perfectamente por el foro, donde te ayudaremos si podemos/sabemos.


Un saludo
__________________
If to err is human, then programmers are the most human of us
  #7 (permalink)  
Antiguo 01/04/2015, 09:02
Avatar de veniwarez  
Fecha de Ingreso: julio-2010
Mensajes: 110
Antigüedad: 13 años, 9 meses
Puntos: 3
Respuesta: Leer XML varios bucles.

Con la salida que me da no tengo forma de saber a que ciudad pertenece cada día ya que primero me lee todos las ciudades y despues me lee los dias. La idea es leer una ciudad entonces leer sus dias para asi poder añadirselos.
  #8 (permalink)  
Antiguo 01/04/2015, 09:35
Avatar de Profesor_Falken  
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Leer XML varios bucles.

Buenas,

Sigues sin poner un ejemplo de la salida que esperas y no se entiende lo que quieres.


Te refieres a que quieres agrupar por ciudad?

Por lo que veo, es lo que ya estas haciendo. Torremolinos3 agrupa las dos fechas existentes, luego tu problema sigue siendo un misterio:



----------------------------------
CITY: Torremolinos1
PROVINCE: Malaga
----------------------------------
**************************
DIA: 2111-11-11 nomTorremolinos1
TEMP MAX:1.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8

----------------------------------
CITY: Torremolinos2
PROVINCE: Malaga
----------------------------------
**************************
DIA: 2111-01-14 nomTorremolinos2
TEMP MAX:2.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8
----------------------------------
CITY: Torremolinos3
PROVINCE: Malaga
----------------------------------
**************************
DIA: 2111-01-18 nomTorremolinos3
TEMP MAX:3.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8
**************************
DIA: 2222-11-12 nomTorremolinos3
TEMP MAX:4.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8
__________________
If to err is human, then programmers are the most human of us
  #9 (permalink)  
Antiguo 01/04/2015, 09:43
Avatar de veniwarez  
Fecha de Ingreso: julio-2010
Mensajes: 110
Antigüedad: 13 años, 9 meses
Puntos: 3
Respuesta: Leer XML varios bucles.

Perdón el Output que puse es el que deseo o sea como deberia leerse la información pero el output que tengo y la forma en la que lee la informacion es asi:

----------------------------------
CITY: Torremolinos1
PROVINCE: Malaga
----------------------------------
----------------------------------
CITY: Torremolinos2
PROVINCE: Malaga
----------------------------------
----------------------------------
CITY: Torremolinos3
PROVINCE: Malaga
----------------------------------
**************************
DIA: 2111-11-11 nomTorremolinos3
TEMP MAX:1.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8
**************************
DIA: 2111-01-14 nomTorremolinos3
TEMP MAX:2.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8
**************************
DIA: 2133-01-14 nomTorremolinos3
TEMP MAX:2.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8
**************************
DIA: 2111-01-18 nomTorremolinos3
TEMP MAX:3.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8
**************************
DIA: 2222-11-12 nomTorremolinos3
TEMP MAX:4.0
TEMP MIN:7.0
TEMP AVE:8.7
TEMP VMAX:8.0
TEMP VRATXA:28.0
TEMP PREC:29.8



Primero lee las ciudades y despues el tiempo y claro la ultima ciudad leida fue Torremolinos3 por eso en todos los dias aparece torremolinos3.

Perdon por ese error.
  #10 (permalink)  
Antiguo 01/04/2015, 12:56
Avatar de Profesor_Falken  
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Leer XML varios bucles.

Buenas,

El código hace exactamente lo que le pides. Si no lo entiendes lo que estás programando, deberías empezar a estudiar lo más básico antes de empezar a hacer prueba/error.

Sin que sirva de precedente, lo he retocado para que te funcione. Intenta estudiarlo y entenderlo para que al menos el tiempo que le he dedicado sirva para algo:

Código Java:
Ver original
  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.text.ParseException;
  4.  
  5. import javax.xml.parsers.DocumentBuilder;
  6. import javax.xml.parsers.DocumentBuilderFactory;
  7. import javax.xml.parsers.ParserConfigurationException;
  8.  
  9. import org.w3c.dom.Document;
  10. import org.w3c.dom.Element;
  11. import org.w3c.dom.NodeList;
  12. import org.xml.sax.SAXException;
  13.  
  14. public class main {
  15.  
  16.     /**
  17.      * Run the examples of use org.apache.commons.cli for arguments and read XML
  18.      * file the construct the object {@link Lecturer}
  19.      *
  20.      * @param args
  21.      *            -h | -f path/of/file.xml
  22.      * @throws ParseException
  23.      * @throws IOException
  24.      * @throws ParserConfigurationException
  25.      * @throws SAXException
  26.      */
  27.     public static void main(String[] args) throws ParseException, IOException,
  28.             ParserConfigurationException, SAXException {
  29.         inicialitzar();
  30.  
  31.     }
  32.  
  33.     public static void inicialitzar() throws ParseException, IOException,
  34.             ParserConfigurationException, SAXException {
  35.         String fileName = "xml/dades2.xml";
  36.         /**
  37.          * Read XML file
  38.          */
  39.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  40.         DocumentBuilder builder = factory.newDocumentBuilder();
  41.         File file = new File(fileName);
  42.         Document document = builder.parse(file);
  43.  
  44.         // Return ed element of XML file.
  45.         Element ed = document.getDocumentElement();
  46.         String name = "";
  47.         String province = "";
  48.         // Return lecturer elements list
  49.         NodeList lecturerList = ed.getElementsByTagName("Ciutat");
  50.         if (lecturerList != null && lecturerList.getLength() > 0) {
  51.             for (int i = 0; i < lecturerList.getLength(); i++) {
  52.  
  53.                 // Get a lecturer
  54.                 Element lecturer = (Element) lecturerList.item(i);
  55.  
  56.                 // Get lecturer's name label
  57.                 name = new String();
  58.                 NodeList nameList = lecturer.getElementsByTagName("Nom");
  59.                 if (nameList != null && nameList.getLength() > 0) {
  60.                     Element nameElement = (Element) nameList.item(0);
  61.                     name = nameElement.getFirstChild().getNodeValue();
  62.  
  63.                 }
  64.                 // Get lecturer's name label
  65.                 province = new String();
  66.                 NodeList provinceList = lecturer
  67.                         .getElementsByTagName("Provincia");
  68.                 if (provinceList != null && provinceList.getLength() > 0) {
  69.                     Element nameElement = (Element) provinceList.item(0);
  70.                     province = nameElement.getFirstChild().getNodeValue();
  71.  
  72.                 }
  73.                 // tco=new TempsCiutatOrdenat(name,province,maxim);
  74.                 System.out.println("----------------------------------");
  75.  
  76.                 System.out.println(" CITY: " + name);
  77.  
  78.                 System.out.println(" PROVINCE: " + province);
  79.                 System.out.println("----------------------------------");
  80.  
  81.                 String dia = "";
  82.                 float tempMax = 0F;
  83.                 float tempMin = 0F;
  84.                 float tempAve = 0F;
  85.                 float vMax = 0F;
  86.                 float vRatxa = 0F;
  87.                 float prec = 0F;
  88.                 NodeList dadesList = lecturer.getElementsByTagName("Dades");
  89.                 NodeList dadaList = ((Element) dadesList.item(0))
  90.                         .getElementsByTagName("Dada");
  91.                 for (int j = 0; j < dadaList.getLength(); j++) {
  92.                     Element lecturer2 = (Element) dadaList.item(j);
  93.                     dia = lecturer2.getAttribute("dia");
  94.                     // Get a lecturer
  95.  
  96.                     // Get lecturer's name label
  97.                     NodeList tempMaxList = lecturer2
  98.                             .getElementsByTagName("TempMax");
  99.                     if (tempMaxList != null && tempMaxList.getLength() > 0) {
  100.                         Element nameElement = (Element) tempMaxList.item(0);
  101.                         tempMax = Float.parseFloat(nameElement.getFirstChild()
  102.                                 .getNodeValue());
  103.  
  104.                     }
  105.                     // Get lecturer's name label
  106.  
  107.                     NodeList tempMinList = lecturer2
  108.                             .getElementsByTagName("TempMin");
  109.                     if (tempMinList != null && tempMinList.getLength() > 0) {
  110.                         Element nameElement = (Element) tempMinList.item(0);
  111.                         tempMin = Float.parseFloat(nameElement.getFirstChild()
  112.                                 .getNodeValue());
  113.                     }
  114.  
  115.                     NodeList tempAveList = lecturer2
  116.                             .getElementsByTagName("TempAve");
  117.                     if (tempAveList != null && tempAveList.getLength() > 0) {
  118.                         Element nameElement = (Element) tempAveList.item(0);
  119.                         tempAve = Float.parseFloat(nameElement.getFirstChild()
  120.                                 .getNodeValue());
  121.                     }
  122.  
  123.                     NodeList vMaxList = lecturer2.getElementsByTagName("VMax");
  124.                     if (vMaxList != null && vMaxList.getLength() > 0) {
  125.                         Element nameElement = (Element) vMaxList.item(0);
  126.                         vMax = Float.parseFloat(nameElement.getFirstChild()
  127.                                 .getNodeValue());
  128.                     }
  129.  
  130.                     NodeList vRatxaList = lecturer2
  131.                             .getElementsByTagName("VRatxa");
  132.                     if (vRatxaList != null && vRatxaList.getLength() > 0) {
  133.                         Element nameElement = (Element) vRatxaList.item(0);
  134.                         vRatxa = Float.parseFloat(nameElement.getFirstChild()
  135.                                 .getNodeValue());
  136.                     }
  137.  
  138.                     NodeList precList = lecturer2.getElementsByTagName("Prec");
  139.                     if (precList != null && precList.getLength() > 0) {
  140.                         Element nameElement = (Element) precList.item(0);
  141.                         prec = Float.parseFloat(nameElement.getFirstChild()
  142.                                 .getNodeValue());
  143.                     }
  144.                     /*
  145.                      * DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd"); Date
  146.                      * data1 = d1.parse(dia);
  147.                      */
  148.                     // tco.afegirTempsDia(data1, tempMax, tempMin, tempAve,
  149.                     // vMax, vRatxa, prec);
  150.  
  151.                     System.out.println("**************************");
  152.                     System.out.println(" DIA: " + dia + " nom" + name);
  153.                     System.out.println(" TEMP MAX:" + tempMax);
  154.                     System.out.println(" TEMP MIN:" + tempMin);
  155.                     System.out.println(" TEMP AVE:" + tempAve);
  156.                     System.out.println(" TEMP VMAX:" + vMax);
  157.                     System.out.println(" TEMP VRATXA:" + vRatxa);
  158.                     System.out.println(" TEMP PREC:" + prec);
  159.                 }
  160.  
  161.             }
  162.         }
  163.     }
  164. }

Un saludo
__________________
If to err is human, then programmers are the most human of us
  #11 (permalink)  
Antiguo 01/04/2015, 13:20
Avatar de veniwarez  
Fecha de Ingreso: julio-2010
Mensajes: 110
Antigüedad: 13 años, 9 meses
Puntos: 3
Respuesta: Leer XML varios bucles.

Gracias, no puedo ver todo el codigo que has puesto debido al Highligh, por eso lo no lo usé.

Yo quiero aprender el problema es cuando el profesor te dice: Toma aquí tienes un ejemplo y apañate para hacer esto, esto, esto y lo otro para la semana que viene.
Yo no se mucho de programación pero he intentado aplicar todo lo que se para solucionar esto.
  #12 (permalink)  
Antiguo 02/04/2015, 00:44
Avatar de Profesor_Falken  
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Leer XML varios bucles.

Cita:
no puedo ver todo el codigo que has puesto debido al Highligh, por eso lo no lo usé.
Como que no lo puedes ver? Tiene una barra de scroll. Solo tienes que bajar.
__________________
If to err is human, then programmers are the most human of us
  #13 (permalink)  
Antiguo 02/04/2015, 03:48
Avatar de veniwarez  
Fecha de Ingreso: julio-2010
Mensajes: 110
Antigüedad: 13 años, 9 meses
Puntos: 3
Respuesta: Leer XML varios bucles.

A si? A mi no me aparece barra de scroll. A mi a partir de la línea 39 desaparece además se solapa con "Un saludo". :-/ Debe ser algo mio entonces.
Gracias por todo.
  #14 (permalink)  
Antiguo 02/04/2015, 03:57
Avatar de Profesor_Falken  
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Leer XML varios bucles.

Actualiza o prueba en otro navegador. Te deberia aparecer.

De cualquier forma te lo pego aqui sin hightlight:

import java.io.File;
import java.io.IOException;
import java.text.ParseException;

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 main {

/**
* Run the examples of use org.apache.commons.cli for arguments and read XML
* file the construct the object {@link Lecturer}
*
* @param args
* -h | -f path/of/file.xml
* @throws ParseException
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
public static void main(String[] args) throws ParseException, IOException,
ParserConfigurationException, SAXException {
inicialitzar();

}

public static void inicialitzar() throws ParseException, IOException,
ParserConfigurationException, SAXException {
String fileName = "xml/dades2.xml";
/**
* Read XML file
*/
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File(fileName);
Document document = builder.parse(file);

// Return ed element of XML file.
Element ed = document.getDocumentElement();
String name = "";
String province = "";
// Return lecturer elements list
NodeList lecturerList = ed.getElementsByTagName("Ciutat");
if (lecturerList != null && lecturerList.getLength() > 0) {
for (int i = 0; i < lecturerList.getLength(); i++) {

// Get a lecturer
Element lecturer = (Element) lecturerList.item(i);

// Get lecturer's name label
name = new String();
NodeList nameList = lecturer.getElementsByTagName("Nom");
if (nameList != null && nameList.getLength() > 0) {
Element nameElement = (Element) nameList.item(0);
name = nameElement.getFirstChild().getNodeValue();

}
// Get lecturer's name label
province = new String();
NodeList provinceList = lecturer
.getElementsByTagName("Provincia");
if (provinceList != null && provinceList.getLength() > 0) {
Element nameElement = (Element) provinceList.item(0);
province = nameElement.getFirstChild().getNodeValue();

}
// tco=new TempsCiutatOrdenat(name,province,maxim);
System.out.println("----------------------------------");

System.out.println(" CITY: " + name);

System.out.println(" PROVINCE: " + province);
System.out.println("----------------------------------");

String dia = "";
float tempMax = 0F;
float tempMin = 0F;
float tempAve = 0F;
float vMax = 0F;
float vRatxa = 0F;
float prec = 0F;
NodeList dadesList = lecturer.getElementsByTagName("Dades");
NodeList dadaList = ((Element) dadesList.item(0))
.getElementsByTagName("Dada");
for (int j = 0; j < dadaList.getLength(); j++) {
Element lecturer2 = (Element) dadaList.item(j);
dia = lecturer2.getAttribute("dia");
// Get a lecturer

// Get lecturer's name label
NodeList tempMaxList = lecturer2
.getElementsByTagName("TempMax");
if (tempMaxList != null && tempMaxList.getLength() > 0) {
Element nameElement = (Element) tempMaxList.item(0);
tempMax = Float.parseFloat(nameElement.getFirstChild()
.getNodeValue());

}
// Get lecturer's name label

NodeList tempMinList = lecturer2
.getElementsByTagName("TempMin");
if (tempMinList != null && tempMinList.getLength() > 0) {
Element nameElement = (Element) tempMinList.item(0);
tempMin = Float.parseFloat(nameElement.getFirstChild()
.getNodeValue());
}

NodeList tempAveList = lecturer2
.getElementsByTagName("TempAve");
if (tempAveList != null && tempAveList.getLength() > 0) {
Element nameElement = (Element) tempAveList.item(0);
tempAve = Float.parseFloat(nameElement.getFirstChild()
.getNodeValue());
}

NodeList vMaxList = lecturer2.getElementsByTagName("VMax");
if (vMaxList != null && vMaxList.getLength() > 0) {
Element nameElement = (Element) vMaxList.item(0);
vMax = Float.parseFloat(nameElement.getFirstChild()
.getNodeValue());
}

NodeList vRatxaList = lecturer2
.getElementsByTagName("VRatxa");
if (vRatxaList != null && vRatxaList.getLength() > 0) {
Element nameElement = (Element) vRatxaList.item(0);
vRatxa = Float.parseFloat(nameElement.getFirstChild()
.getNodeValue());
}

NodeList precList = lecturer2.getElementsByTagName("Prec");
if (precList != null && precList.getLength() > 0) {
Element nameElement = (Element) precList.item(0);
prec = Float.parseFloat(nameElement.getFirstChild()
.getNodeValue());
}
/*
* DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd"); Date
* data1 = d1.parse(dia);
*/
// tco.afegirTempsDia(data1, tempMax, tempMin, tempAve,
// vMax, vRatxa, prec);

System.out.println("**************************");
System.out.println(" DIA: " + dia + " nom" + name);
System.out.println(" TEMP MAX:" + tempMax);
System.out.println(" TEMP MIN:" + tempMin);
System.out.println(" TEMP AVE:" + tempAve);
System.out.println(" TEMP VMAX:" + vMax);
System.out.println(" TEMP VRATXA:" + vRatxa);
System.out.println(" TEMP PREC:" + prec);
}

}
}
}
}

Un saludo
__________________
If to err is human, then programmers are the most human of us
  #15 (permalink)  
Antiguo 02/04/2015, 04:50
Avatar de veniwarez  
Fecha de Ingreso: julio-2010
Mensajes: 110
Antigüedad: 13 años, 9 meses
Puntos: 3
Respuesta: Leer XML varios bucles.

Gracias, no se que debe ser.

Etiquetas: clase, xml
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:30.