Check if TAG XML exists

1

I am writing a code that reads data from an XML returned by hardware, but some TAG now has not and can not check the existence of it.

Follow the code used to read the XML and use the data.

 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();
    .....

But if TAG <CPF> does not exist return Nullpointer exception how to check if there is the relevant information.

    
asked by anonymous 28.03.2016 / 20:21

1 answer

0

I did as follows and it worked:

XML

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

Mapping:

@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;
    }
}

Test

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());
}

The call cfe.getInfCfe().getDest().getCpf() returns null if the tag does not exist. The problem may be in your mapping. Try to map the way I showed you.

    
30.07.2016 / 15:18