1

Estou escrevendo um código que faça a leitura de dados de um XML retornado por equipamento, porém algumas TAG ora tem ora não tem e não consigo verificar a existência do mesmo.

Segue o código utilizado para ler o XML e utilizar os dados.

 public void lerXml(String xml) {

    String xmlFilePathNFe3 = xml;
    JAXBContext context = null;
    CFe cfe = null;

    try {

        context = JAXBContext.newInstance(CFe.class.getPackage().getName());

        Unmarshaller unmarshaller1 = context.createUnmarshaller();

        cfe = (CFe) unmarshaller1.unmarshal(new File(xmlFilePathNFe3));

    } catch (JAXBException ex) {
        ex.printStackTrace();
    }

    String exemploCpf = cfe.getInfCFe().getDest().getCPF();
    .....

Porém se a TAG <CPF> não existir retorna exceção Nullpointer como verificar se existe a referente informação.

2
  • O NullPointer acontece no unmarshal ou no getCPF()? 30/07/2016 às 12:54
  • Sim o NullPointer ocorre quando tento atribuir o valor dentro do getCPF() em um objeto, sendo que este getCPF() não é existente naquele XML.
    – DevAgil
    23/08/2016 às 17:25

1 Resposta 1

0

Fiz da seguinte forma e funcionou:

XML

<cfe>
    <infCfe>
        <dest>
        </dest>
    </infCfe>
</cfe>

Mapeamento:

@XmlRootElement(name = "cfe")
public class Cfe {
    private InfCfe infCfe;

    public InfCfe getInfCfe() {
        return infCfe;
    }

    public void setInfCfe(InfCfe infCfe) {
        this.infCfe = infCfe;
    }
}

public class InfCfe {
    private Dest dest;

    public Dest getDest() {
        return dest;
    }

    public void setDest(Dest dest) {
        this.dest = dest;
    }
}

public class Dest {
    private String cpf;

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }
}

Teste

public static void main(String args[]) {
    String path = "";
    Cfe cfe = null;

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Cfe.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        cfe = (Cfe) jaxbUnmarshaller.unmarshal(new File(path));
    } catch (JAXBException e) {
        e.printStackTrace();
    }

    System.out.println(cfe.getInfCfe().getDest().getCpf());
}

A chamada cfe.getInfCfe().getDest().getCpf() retorna null se a tag não existir. O problema pode estar no seu mapeamento. Tente mapear da forma que eu mostrei.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .