Nuri Ensing
Nuri Ensing

Reputation: 2030

simpler way of checking if xml elements exist

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){

Upvotes: 2

Views: 3022

Answers (2)

jschnasse
jschnasse

Reputation: 9598

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

Upvotes: 1

Andremoniy
Andremoniy

Reputation: 34920

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.

Upvotes: 0

Related Questions