Question: In Java I parse an xml by using the dom parser..
I wanted to know is it needed for every element to check if the element is present in XML or not..

For example now I do this check when saving an value which is inside an element:

```
 //Email
 NodeList nListEmail = BuyerPartyElement.getElementsByTagName("Email");
 if(nListEmail.getLength() != 0){
   docOrder.replaceItemValue("BestellerEmail", nListEmail.item(0).getTextContent());
 }

```

But is this is a must for every element? Because if the element is non existent in 1 XML then i will get a null error I think.

any ideas?

Edit:

to make it simpler I created two methods for this:

```
    public Element getElement(NodeList nodeList, String ElementName){
         if(nodeList.getLength() != 0){
             return (Element) nodeList.item(0);
         }else{
             System.out.println("ELEMENT : " + ElementName + " NOT EXISTING IN XML");
             return null;
         }
    }

    public String getValueFromElement(Element element, String ElementName){

        NodeList nodeList = element.getElementsByTagName(ElementName);
        if(nodeList.getLength() != 0){
             return nodeList.item(0).getTextContent();
         }else{
             System.out.println("ELEMENT : " + ElementName + " NOT EXISTING IN XML");
             return null;
         }

    }

```

then later i will check:

```
if(CXMLHandlerObj.getValueFromElement(buyerPostalAddressElement, "City") != null){

```

Answer: 
You can [validate your XML input against](https://stackoverflow.com/a/43339306/1485527) an [XML-Schema](https://www.w3.org/TR/xmlschema11-1/) to make sure that the document has the assumed structure. This will save you some null checks.

I'd also recommend to use [XPath](https://stackoverflow.com/questions/3939636/how-to-use-xpath-on-xml-docs-having-default-namespace) to navigate within your dom. This will save you some additional checks.

If your code is still bloated with null checks you can consider to use [Java 8 Optionals](http://blog.jhades.org/java-8-how-to-use-optional/)
The answer is very simple. 

In Java language you *have* to check all variables which can be `null` before accessing them.

In Java language you *have* to check all array or list variables for their size before accessing to their elements by index.