Vithushan
Vithushan

Reputation: 513

Get attributes of a given XML element using JAVA

Here is the XML file:

<TestCase name="SearchPromotions" type="DDTC" recovery="false" datatable="HsbcDemoSearchPromotionstestCaseSpecificVirtualDatatable" position="0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="file://C:/New folder/VTAF/base-qa-3.0.5.2/generator/xsd/TestCase.xsd">

    <SelectedDataTableNames name="SearchData"> </SelectedDataTableNames>

    <Open page="hsbc"  ms="5000"  />
    <Click object="hsbc.Personal_Link"  />
    <Click object="hsbc.CreditCard_tab"  />
    <Call businessComponent="Global.Verify_Search">
       <Param name="HotelName_Param" value="@SearchData_link" />
    </Call>
    <CheckElementPresent object="hsbc.Img_Hotel_logo"  Identifire="Hotel_Name_PARAM:@SearchData_ResultHotelName"  fail="true"  customErrorMessage="Searched hotel name is not present in the page."  />
</TestCase>

And Here is the java code to get the attributes from a specified element. If i try to run it is giving NullpointException. I dont know what is missing or what is the fault. Please can anyone help me out. I have commented the lines where the exception occurs:

File fXmlFile = new File("SearchPromotions.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

Element docEle = doc.getDocumentElement();
NodeList nl = docEle.getChildNodes();

if (nl != null && nl.getLength() > 0) {
    for (int i = 0; i < nl.getLength(); i++) {
        if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element ele = (Element) nl.item(i);

            switch(ele.getNodeName()){
                case "Click":
                    System.out.println(ele);
                    //----------------
                    System.out.println(ele.getAttributes().getNamedItem("page").getNodeValue());
                    //----------------
                    break;
                default:
                    break;
            }
        }
    }
}

Upvotes: 1

Views: 102

Answers (2)

Nimelrian
Nimelrian

Reputation: 1716

You're trying to get the page attribute of a Click element, but it only holds an object attribute.

Thus, when executing ele.getAttributes().getNamedItem("page").getNodeValue() getNamedItem("page") will return null.

Upvotes: 1

Smutje
Smutje

Reputation: 18123

Your elements

<Click object="hsbc.Personal_Link"  />
<Click object="hsbc.CreditCard_tab"  />

have no attribute named "page", only an attribute named "object", so the accessing via

ele.getAttributes().getNamedItem("page").getNodeValue();

has to result in a NullPointerException. The only element having a "page" attribute is

<Open page="hsbc"  ms="5000"  />

Upvotes: 1

Related Questions