Como eu faço para gravar, salvar e ler arquivos xml em java…??
no python eu utilizo dom a qual eu tenho eu tem uma bliblioteca que me permite criar nodes no xml dinâmicamente no java existe isto…?
Eu tenho um exemplo para vc ae… enjoy!
import java.io.*;
// DOM
import org.w3c.dom.*;
// Xerces classes
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.*;
/**
* @author Gabriel
*/
public class dom_xerces {
private String filename="teste.xml";
/** Creates a new instance of dom_xerces */
public dom_xerces() throws FileNotFoundException, IOException {
Element e = null;
Node n = null;
// Document (Xerces implementation only).
Document xmldoc= new DocumentImpl();
// Root element.
Element root = xmldoc.createElement("USERS");
String[] id = {"PWD122","MX787","A4Q45"};
String[] type = {"customer","manager","employee"};
String[] desc = {"Tim@Home","Jack&Moud","John D'oé"};
for (int i=0;i<id.length;i++)
{
// Child i.
e = xmldoc.createElementNS(null, "USER");
e.setAttributeNS(null, "ID", id[i]);
e.setAttributeNS(null, "TYPE", type[i]);
n = xmldoc.createTextNode(desc[i]);
e.appendChild(n);
root.appendChild(e);
}
xmldoc.appendChild(root);
FileOutputStream fos = new FileOutputStream(filename);
// XERCES 1 or 2 additionnal classes.
OutputFormat of = new OutputFormat("XML","ISO-8859-1",true);
of.setIndent(1);
of.setIndenting(true);
of.setDoctype(null,"users.dtd");
XMLSerializer serializer = new XMLSerializer(fos,of);
// As a DOM Serializer
serializer.asDOMSerializer();
serializer.serialize( xmldoc.getDocumentElement() );
fos.close();
}
public static void main(String[] args) throws FileNotFoundException, IOException {
new dom_xerces();
}
}