jueves, febrero 21, 2008

XML contrataca!!

Bueno... para recordar... hace tiempo tuve un problema pasando un XML
por post... y leyendo la respuesta tambien por Post... bien.. ahora
explicare que hize...



Primero dire que java tiene dos
Decodificadores de XML el DocumentBuilder y el SAXParser... aqui solo
hablare de el primero... a mi parecer es mas facil de usar...



Primero imaginemos que recibiremos un XML asi

<gente>

   
<persona nombre="Danyel">


   
    <materia nombre="BD"/>


   
    <materia nombre="SO"/>


   
</persona>


</gente>



Lo primero creo el XML a mano... como no es muy complejo en mi caso..
no hizo falta utilizar los codificadores de java..



String xml = ""



Llamo a la funcion



builder =
javax.xml.parsers.DocumentBuilderFactory.newInstance();


doc =
builder.newDocumentBuilder();


d= doc.parse(xmlPOSTIS(s));



Despues lo mando a la URL



public org.xml.sax.InputSource
xmlPOSTIS(String s) {


   
org.xml.sax.InputSource is;


   
//Se conecta


   
try {


   
    java.net.URL url = new
java.net.URL("https://paginasegura.com");


   
    java.net.HttpURLConnection
httpurl = (java.net.HttpURLConnection)url.openConnection();


   
    //Abre las entradas y las salidas


   
    httpurl.setDoInput(true);


   
    httpurl.setDoOutput(true);


   
    java.io.DataOutputStream out =
new java.io.DataOutputStream(httpurl.getOutputStream());


   
    //Escribe en el stream de salida
un docuemtno XML


   
    for (int i=0;i<s.length();i++) {


   
       
out.write(s.charAt(i));


   
    }


   
    //Convierte el InputSream de
entrada en un Parser


   
    is = new
org.xml.sax.InputSource(httpurl.getInputStream());


   
    return is;


   
}catch(Exception e) {


   
    System.out.println(e.getMessage());


   
    return null;


    }

}



Ahora ya obteniendo el inputSource ya procedo a decodificarlo de la
siguiente manera



java.util.LinkedList cat = new
java.util.LinkedList();


//Son todos los elementos con el
tag error es decir


org.w3c.dom.NodeList lista =
d.getElementsByTagName("persona");


for (int
i=0;i<lista.getLength();i++) {

    String aux =
lista.item(i).getAttributes().getNamedItem("category").getNodeValue();

    for (int j = 0; j <
lista.item(i).getChildNodes().getLength(); j++) {

       
lista.item(i).getChildNodes().item(j);

    }

}


Bueno espero que le haya servido a mas de uno... si tienes cualquier duda o comentario pregunta!! :D