Leitura XML informações dobradas ((Resolvido))

2 respostas
H

Pessoal, enviei outro pedido no qual já consegui resolver, o meu problema agora é:

tenho o código:

<cep>34123-145</cep> <telefone> 41-3212-3345</telefone> <uf>MG</uf>

porem esse codigo pode vir assim:

<cep>34123-145</cep> <telefone> 41-3212-3345</telefone> <telefone> 41-3212-3345</telefone> <uf>MG</uf>

como eu faria a leitura nesse caso? tentei utilizar um for só que não deu muito certo…, tem alguma forma de passar o elemento “telefone” e ele retorna a lista?

2 Respostas

glprog

Boa tarde himorrivel.

Tente assim:

package teste;

import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class LeituraXML {

    public static void main(String[] args) {
        try {
            DOMParser dom = new DOMParser();
            dom.parse("CAMINHO DO SEU XML");
            Document doc = dom.getDocument();
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList listNode = (NodeList) xPath.compile("//telefone").evaluate(doc, XPathConstants.NODESET);
            if (listNode != null) {
                for (int i = 0; i < listNode.getLength(); i++) {
                    Node node = listNode.item(i);
                    System.out.println(node.getNodeName() + " " + node.getTextContent());
                }
            }

        } catch (Exception e) {
            System.out.println("Erro: " + e.getMessage());
        }

    }

}
H

NodeList listaTeste = elemento.getElementsByTagName("telefone"); for (int j = 0; j < listaTeste.getLength(); j++) { Node node = listaTeste.item(j); System.out.println(node.getNodeName() + " " + node.getTextContent()); }

obrigado, resolveu meu problema

Criado 20 de maio de 2015
Ultima resposta 20 de mai. de 2015
Respostas 2
Participantes 2