使用JAVA获取给定XML元素的属性

时间:2014-09-24 09:12:53

标签: java xml

这是XML文件:

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

以下是从指定元素获取属性的java代码。如果我尝试运行它是给NullpointException。我不知道缺少什么或者是什么错。请任何人帮助我。我已经评论了发生异常的行:

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;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

你的元素

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

没有名为&#34; page&#34;的属性,只有一个名为&#34; object&#34;的属性,所以通过

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

必须产生NullPointerException。唯一具有&#34;页面的元素&#34;属性是

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

答案 1 :(得分:1)

您尝试获取page元素的Click属性,但它只包含object属性。

因此,执行ele.getAttributes().getNamedItem("page").getNodeValue() getNamedItem("page")时会返回null