Este post es un esbozo
Supongamos que el archivo “foo.xml” es el siguiente:
<tienda nombre="tienda para geeks" ubicacion="Tokio, Japon"><computadora nombre="iBook" precio="$1200" /><historieta nombre="Dragon Ball Volumen 1" precio="$9" /><nivel_geek_de_la_tienda precio="sin precio" /></tienda>
Es posible parsear el documento XML en un árbol de objetos Javas con JDom:
SAXBuilder builder = new SAXBuilder ();Document doc = builder.build (new FileInputStream ("foo.xml"));Element root = doc.getRootElement ();// devuelve "tienda"
root.getName ();// devuelve "tienda para geeks"
root.getAttributeValue ("nombre");// devuelve "Tokio, Japon"
root.getAttributeValue ("ubicacion");// devuelve una List de objetos// que tiene tres Element
root.getChildren ();
También es posible realizar el proceso inverso, es decir construir un árbol de elementos y luego crear un archivo XML:
Element root = new Element ("tienda");root.setAttribute ("nombre", "tienda para geeks");root.setAttribute ("ubicación", "Tokio, Japon");Element item1 = new Element ("computadora");item1.setAttribute ("nombre", "iBook");item1.setAttribute ("precio", "$1200");root.addContent (item1);/* Realizamos lo mismo con los elementos restantes */XMLOutputter outputter = new XMLOutputter ("",true);try{ outputter.output (new Document(root), new FileOutputStream ("foo2.xml"));}catch (Exception e){ e.getMessage();}
Referencias
Sun: Manipulating Contents with DOM
W3C DOM
