Ler arquivo XML do projeto

5 respostas
ThiagoWorldCoder

Olá pessoal?!!

Alguém sabe como ler um arquivo xml do seu projeto?

por exemplo, ele está na pasta META-INF do meu projeto, é um xml chamado context.xml e eu quero pegar alguns dados deste arquivo, como faço isso?!

5 Respostas

Michel_Sancovich

Estuda sobre parser xml.
Vc terá que criar 3 classes: DAO, Parser, TO.
Dao para conectar ao banco…
Parser para ler o arquivo…
e To = Transfer Object ( objeto de transferencia para salvar no banco)

ThiagoWorldCoder

Eu não estou querendo salvar nada no banco, só quero pegar os dados de um arquivo xml que está no meu projeto!

ramilani12

Olá

Procure por JDOM http://www.jdom.org/downloads/docs.html

Michel_Sancovich

O parser:

package br.com.empresa.projeto.xml.parser;

import java.util.ArrayList;
import java.util.Collection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

//Runner.java
import br.com.empresa.projeto.xml.Runner;
//Transfer Object
import br.com.empresa.projeto.xml.to.Usuario;

public class ProcessUsers {
	
	public static Collection<Usuario> processUsers(String fileName) throws ProcessUsersException {
		Collection<Usuario> usuarios = new ArrayList<Usuario>();
		
		Element empresa = processDocument(fileName);
		NodeList nodeList = empresa.getChildNodes();
		
		for(int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if(node.getNodeType() == Node.ELEMENT_NODE) {
				Element element = (Element) node;
				if(element.getNodeName().equals("usuario")) {
					usuarios.add(processUser(element));
				}
			}
		}
		return usuarios;
	}
	
	private static Element processDocument(String fileName) throws ProcessUsersException {
		Element element = null;
		try {
			DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = documentBuilder.parse(Runner.class.getResource(fileName).getPath());
			NodeList nodeList = document.getChildNodes();
			
			if(nodeList.getLength() != 1) {
				throw new ProcessUsersException("XML inválido.");
			}
			Node node = nodeList.item(0);
			if(node.getNodeType() != Node.ELEMENT_NODE) {
				throw new ProcessUsersException("XML inválido.");
			}
			element = (Element) node;
			if(!element.getNodeName().equals("empresa")) {
				throw new ProcessUsersException("XML inválido.");
			}
		} catch(ProcessUsersException e) {
			throw e;
		} catch (Exception e) {
			throw new ProcessUsersException("XML inválido.", e);
		}
		return element;
	}

	private static Usuario processUser(Element element){
		Usuario usuario = new Usuario();
		
		NodeList nodeList = element.getChildNodes();
		
		usuario.setId(Integer.parseInt(element.getAttribute("id")));
		
		for(int  i = 0; i < nodeList.getLength(); i++){
			
			Node node = nodeList.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE){
				
				Element childElement = (Element) node;
				
				if (childElement.getNodeName().equals("nome")) {
					usuario.setNome(childElement.getTextContent());
				}
				else if (childElement.getNodeName().equals("idade")){
					usuario.setIdade(Integer.parseInt(childElement.getTextContent()));
				}
				else if (childElement.getNodeName().equals("email")){
					usuario.setEmail(childElement.getTextContent());
				}
			}
		}
		return usuario;
	}
}

Runner:

public class Runner {
	
	public static void main(String[] args) throws ProcessUsersException, DAOException {
		UsuarioDAO usuarioBanco = new UsuarioDAO();
		
		Collection<Usuario> arrayUsuarios = ProcessUsers.processUsers("/cadastro.xml");
		
		for (Iterator<Usuario> iter = arrayUsuarios.iterator(); iter.hasNext();) {
			Usuario usuario = (Usuario) iter.next();
			usuarioBanco.saveContato(usuario);
		}
	}
}

TO:

public class Usuario {
	
	private int id;
	private Integer idade;
	private String nome;
	private String email;
    
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Integer getIdade() {
		return idade;
	}
	public void setIdade(Integer idade) {
		this.idade = idade;
	}
	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
}

DAO (Conexao Banco)

public class ConexaoBanco {

	protected Connection getConnection() throws DAOException {
		String url = "jdbc:postgresql://localhost:5432/usuario";		
		try {
			Class.forName("org.postgresql.Driver");
			Driver dr = DriverManager.getDriver(url);
			Properties info = new Properties();
			info.setProperty("user", "usuario");
			info.setProperty("password", "senha");
			return dr.connect(url, info);
		} catch (ClassNotFoundException e) {
			throw new DAOException(e);
		}
		catch (SQLException e) {
			throw new DAOException(e);
		}
	}
	
	protected void closeConnection(Connection conn) {
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	protected void closeStatement(PreparedStatement stat) {
		if(stat != null) {
			try {
				stat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	protected void closeResultSet(ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

DAO (Usuario DAO)

public class UsuarioDAO extends ConexaoBanco {

	public void saveContato(Usuario usuario) throws DAOException {
		String sql = "insert into usuario (id, nome, idade, email) values (?,?,?,?)";
		Connection conn = null;
		PreparedStatement stat = null;
		
		try {
			conn = getConnection();
			
			stat = conn.prepareStatement(sql);
			stat.setInt(1, usuario.getId());
			stat.setString(2, usuario.getNome());
			stat.setInt(3, usuario.getIdade());
			stat.setString(4, usuario.getEmail());
			stat.execute();
		} catch (SQLException e) {
			throw new DAOException(e);
		} finally {
			closeStatement(stat);
			closeConnection(conn);
		}
	}
}

Exception:

public class ProcessUsersException extends Exception {

	private static final long serialVersionUID = -8263058810974370886L;

	public ProcessUsersException() {
		super();
	}

	public ProcessUsersException(String message) {
		super(message);
	}

	public ProcessUsersException(Throwable cause) {
		super(cause);
	}

	public ProcessUsersException(String message, Throwable cause) {
		super(message, cause);
	}

}
ThiagoWorldCoder

Valeu galera!!

obrigado!

Criado 13 de outubro de 2008
Ultima resposta 13 de out. de 2008
Respostas 5
Participantes 3