Check if XML TAG exists

Asked

Viewed 924 times

1

I am writing a code that reads data from an XML returned by equipment, but some TAG now it has now it does not and I cannot verify the existence of the same.

Follow the code used to read 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 the TAG <CPF> no exist returns exception Nullpointer how to check if there is the relevant information.

  • Nullpointer happens in unmarshal or getCPF()?

  • Yes Nullpointer occurs when I try to assign the value within getCPF() to an object, and this getCPF() does not exist in that XML.

1 answer

0

I did it this way 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;
    }
}

Testing

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.