2

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){
Nuri Ensing
  • 1,899
  • 1
  • 19
  • 42

2 Answers2

1

You can validate your XML input against an XML-Schema to make sure that the document has the assumed structure. This will save you some null checks.

I'd also recommend to use XPath 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

Community
  • 1
  • 1
jschnasse
  • 8,526
  • 6
  • 32
  • 72
0

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.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
  • Thanks for anwser, for checking this I created 2 methods.. Then later on i will check if not null then go further – Nuri Ensing May 03 '17 at 13:44
  • Not everyone agrees: 'I find null checks to be one of the most unnecessary, ridiculous, ugly practices in programming'http://danielroop.com/blog/2009/10/15/why-defensive-programming-is-rubbish/ – jschnasse May 03 '17 at 20:02