Thursday, July 23, 2015

How to handle empty element in XML (Java StAX Parser)

I am not a Software Developer rather a QA person.
I face this problem, while I was writing Selenium Automation Framework in Java. So I am sharing solution i used in it.

Some XML may contains empty elements. i.e. Creation of XML is not under user ownership and You can not prevent XML to have empty elements.

Strange thing is there is no inbuilt function in XMLEvent  API to check empty elements.
Here is tick that you can use:

Example of XML file:
<teststepID tid="S1TC1">
<step>
<action>VisitURL</action>
<locator-id></locator-id>
<locator-class></locator-class>
<locator-xpath></locator-xpath>
<data>http://www.nextag.com/</data>
</step>
<step>
<action>Type</action>
<locator-id>searchTop-s2</locator-id>
<locator-class></locator-class>
<locator-xpath></locator-xpath>
<data>shoes</data>
</step>
</teststepID >

Code to handle:
if (event.isStartElement()) {
        //Check for each element
if (event.asStartElement().getName().getLocalPart().equals(action)) {
                 //After reading element, check for immediate next element. 
         event = eventReader3.nextEvent();
                    //Immediate element should be Endelement  due to empty tag in XML.
            if(event.isEndElement()){    
            }
            else {
                           //Else store the value or use according to your requirement. 
                  td.setStep_action(event.asCharacters().getData());
                  }
                //Continue loop of XML event reader
continue;
}
}



No comments:

Post a Comment