如何在java上获取根节点属性

jha*_*rry 13 java xml eclipse

我有一个像下面的xml文件.我想获得药房节点的纬度和经度属性.我可以获得chilnodes属性但无法获得根节点属性.我是java和xml的新手.我找不到解决办法怎么办.

<pharmacies Acc="4" latitude="36.8673380" longitude="30.6346640" address="Ayujkila">
        <pharmacy name="sadde" owner="" address="dedes" distance="327.000555668" phone="342343" lat="36.8644" long="30.6345" accuracy="8"/>
        <pharmacy name="Sun " owner="" address="degerse" distance="364.450016586" phone="45623" lat="36.8641" long="30.6353" accuracy="8"/>
        <pharmacy name="lara" owner="" address="freacde" distance="927.262190129" phone="564667" lat="36.8731" long="30.6422" accuracy="8"
    <end/>
    </pharmacies>
Run Code Online (Sandbox Code Playgroud)

这是我的代码部分.我从url地址获取xml文件.

                    DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                 DocumentBuilder db = dbf.newDocumentBuilder();
                 Document doc = db.parse(new InputSource(url.openStream()));
                 doc.getDocumentElement().normalize();
                    NodeList nodeList =doc.getElementsByTagName("pharmacy");
                 for (int i = 0; i < nodeList.getLength(); i++){
                      Node node =nodeList.item(i);
                      Element fstElmnt = (Element) node;
                      NodeList pharmacyList = fstElmnt.getElementsByTagName("pharmacy");
                      Element pharmacyElement = (Element) pharmacyList.item(0);
              Element pharmacyElement = (Element) pharmacyList.item(0);

              HashMap<String,String>map=new HashMap<String,String>();                   
              map.put("name", pharmacyElement.getAttribute("name"));
              map.put("distance", pharmacyElement.getAttribute("phone"));
              list.add(map);

              latt.add(pharmacyElement.getAttribute("lat"));

                    ....
Run Code Online (Sandbox Code Playgroud)

ska*_*man 27

<pharmacies>本身可以使用得到的元件

Element pharmacies = doc.getDocumentElement();
Run Code Online (Sandbox Code Playgroud)

您可以从中获取属性.


biz*_*lop 6

doc.getDocumentElement()将返回根元素,您可以getAttribute( attrName )像在任何其他元素上一样调用它.