Ir al contenido principal

Leer cadena XML desde Java

En esta primera entrada sobre XML y Java, se analizará una cadena XML y se imprimirá el resultado, lo primero que tenemos es la cadena XML de Productos:

Supongamos el siguiente XML:



    
  <productos>
    <producto>
        <nombre>Televisor LCD 32'</nombre>
        <precio>3500</precio>
        <stock>5</stock>
        <marca>SONY</marca>
    </producto>
    <producto>
        <nombre>Pantalon jean azul</nombre>
        <precio>159</precio>
        <stock>200</stock>
        <marca>Levis</marca>
    </producto>
    <producto>
        <nombre>Colchon ortopedico King Size</nombre>
        <precio>1250</precio>
        <stock>1</stock>
        <marca>Paraiso</marca>
    </producto>
</productos>


Con el siguiente código se lee y se imprime los elementos de cada producto de la lista de productos:

import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


/**
 *
 * @author mzavaleta
 */
public class Main {


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws SAXException, IOException {
        String cadenaXML =
                "<productos>"
                + "<producto>"
                + "<nombre>Televisor LCD 32'</nombre>"
                + "<precio>3500</precio>"
                + "<stock>5</stock>"
                + "<marca>SONY</marca>"
                + "</producto>"
                + "<producto>"
                + "<nombre>Pantalon jean azul</nombre>"
                + "<precio>159</precio>"
                + "<stock>200</stock>"
                + "<marca>Levis</marca>"
                + "</producto>"
                + "<producto>"
                + "<nombre>Colchon ortopedico King Size</nombre>"
                + "<precio>1250</precio>"
                + "<stock>1</stock>"
                + "<marca>Paraiso</marca>"
                + "</producto>"
                + "</productos>";
        DOMParser parser = new DOMParser();
        parser.parse(new InputSource(new java.io.StringReader(cadenaXML)));


        Document doc = parser.getDocument();
        NodeList nodeLst = doc.getElementsByTagName("producto");
        for (int i = 0; i &lt; nodeLst.getLength(); i++) {
            Element eleProducto = (Element) nodeLst.item(i);


            NodeList nlsNombre = eleProducto.getElementsByTagName("nombre");
            Element eleNombre = (Element) nlsNombre.item(0);
            String strNombre = eleNombre.getFirstChild().getNodeValue();


            NodeList nlsPrecio = eleProducto.getElementsByTagName("precio");
            Element elePrecio = (Element) nlsPrecio.item(0);
            String strPrecio = elePrecio.getFirstChild().getNodeValue();


            NodeList nlsStock = eleProducto.getElementsByTagName("stock");
            Element eleStock = (Element) nlsStock.item(0);
            String strStock = eleStock.getFirstChild().getNodeValue();


            NodeList nlsMarca = eleProducto.getElementsByTagName("marca");
            Element eleMarca = (Element) nlsMarca.item(0);
            String strMarca = eleMarca.getFirstChild().getNodeValue();




            System.out.println("Producto:");
            System.out.println("*********");
            System.out.println("   Nombre      : " + strNombre);
            System.out.println("   Precio (S/.): " + strPrecio);
            System.out.println("   Stock (Und) : " + strStock);
            System.out.println("   Marca       : " + strMarca);
        }
    }
}



Luego de compilar y ejecutar tendremos la siguiente salida:

Producto:
*********
   Nombre: Televisor LCD 32'
   Precio: 3500
   Stock : 5
   Marca : SONY
Producto:
*********
   Nombre: Pantalon jean azul
   Precio: 159
   Stock : 200
   Marca : Levis
Producto:
*********
   Nombre: Colchon ortopedico King Size
   Precio: 1250
   Stock : 1
   Marca : Paraiso



Comentarios

Publicar un comentario

Entradas populares de este blog

Leer Ñ en archivos desde Java

Siempre se me ha presentado este problema, cada vez que leo un archivo desde java, y este contiene caracteres como la Ñ, estos son tomado como símbolos raros: Voy a mostrar el código que ocasiona esta distorsión, el archivo "D:\temporal\prueba.txt", cuyo contenido es: PAÑALES DESCARTABLES ÚTILES DE LIMPIEZA VINO AÑEJO Y el código es el siguiente: import java.io.*; /** * * @author mzavaleta */ public class TestÑ { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here FileInputStream fis = new FileInputStream("D:/temporal/prueba.txt"); InputStreamReader is = new InputStreamReader(fis); BufferedReader bf = new BufferedReader(is); String linea; while ((linea = bf.readLine()) != null) { System.out.println(linea); } bf.close(); ...

Separador decimal en Oracle

Para poder cambiar el separador decimal en Oracle, se puede usar la siguiente sentencia, suponiendo que queremos usar el punto ALTER SESSION SET NLS_NUMERIC_CHARACTERS = '. '; Para usarlo dentro de un procedimiento almacenado, se puede usar la siguiente sentencia: EXECUTE IMMEDIATE('ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ''. '' ') ;

Comparación de campos tipo NCHAR

Normalmente cuando se compara cadenas con campos del tipo NCHAR, se muestra el error: ORA-12704: character set mismatch O en español: ORA-12704: no coincide el juego de caracteres Para evitar este error se puede usar la función CSCONVERT cuya sintaxis es: CSCONVERT(cadena,'NCHAR_CS') Donde cadena es el valor que se quiere pasar a NCHAR. Veamos un ejemplo: Tenemos la tabla TABLA_NCHAR que tiene un solo campo tipo NCHAR: create table TABLA_NCHAR ( CAMPO_NCHAR NCHAR(25) ) Si intentamos hacer el siguiente query: select campo_nchar from tabla_nchar UNION SELECT 'TODOS LOS VALORES' FROM DUAL; select campo_nchar from tabla_nchar UNION SELECT 'TODOS LOS VALORES' FROM DUAL ORA-12704: character set mismatch Se mostrará el error indicado al inicio de este blog, pero si se usa la funcion el query funcionará correctamente: SQL> select campo_nchar from tabla_nchar 2 UNION 3 SELECT CSCONVERT('TODOS LOS VALORES','NCHAR_CS...