Bom dia galera, tudo bem?

Segue uma classe de leitura de arquivos XML em Java!

import java.io.File;

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

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

public class XML implements iXML {
private String arquivo;

/**
* Seta o arquivo XML
*
* @param String nome_arquivo - Nome do arquivo XML
* @return void
*/

public void setArquivo(String nome_arquivo) {
this.arquivo = nome_arquivo;
}

/**
* Pega o arquivo XML
*
* @return void
*/

public String getArquivo() {
return this.arquivo;
}

/**
* Carrega o arquivo XML
*
* @return Document doc
*/

public Document CarregarXML() throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document doc = docBuilder.parse(new File(this.getArquivo()));

return doc;
}

/**
* Le a tag do arquivo XML carregado
*
* @param String tag - Nome da tag a ser lida no arquivo XML
* @return String valor
*/

public String LerTag(String tag) throws Exception {
String valor = “”;

Document doc = this.CarregarXML();

Element elemento = doc.getDocumentElement();
Element eltag = (Element) elemento.getElementsByTagName(tag).item(0);

valor = eltag.getTextContent().toString();
valor = (valor != “”) ? valor : “”;

return valor;
}
}

interface iXML {
public void setArquivo(String nome_arquivo);

public String getArquivo();

public Document CarregarXML() throws Exception;

public String LerTag(String tag) throws Exception;
}

Fim da classe ;) Para utilizar a classe, instancie-a, passe por parâmetro em setArquivo() o nome do arquivo XML e utilize o método LerTag() para ler uma tag especifica no arquivo!

XML xml = new XML(); // Cria o objeto

xml.setArquivo(”NOME_DO_ARQUIVO_XML.xml”);

xml.LerTag(”NOME_DA_TAG_XML”); // Ex: LerTag(”channel”)

É isso galera! Espero ter ajudado ;)

Até mais ^^

Leave a Reply