如何在java中获取xml文件中节点的属性

时间:2016-05-06 12:11:56

标签: java xml

强文我是java的新手,我的代码下载了一个XML文件并解析它。我正在尝试在XML文件中读取“city”(name)的属性。我使用pull解析器来解析XML文件,当我运行程序时,我得到一个错误,我的应用程序不幸停止了,帮助我如何得到城市的名称在这种情况下,这是我的示例XML文件和我的代码的一部分:

   private String camera = "city";
   while (event != XmlPullParser.END_DOCUMENT) {
            String name=myParser.getName();

            switch (event) {
                case XmlPullParser.START_TAG: {

                    break;
                }

                case XmlPullParser.TEXT:
                    text = myParser.getText();
                    break;

                case XmlPullParser.END_TAG:

                  if(name.equals("city")){

                        camera = myParser.getAttributeValue(null,"name");

                        list.add(camera);

                    }

<?xml version="1.0"?>
<current>
   
   <city id="2643743" name="London">
      <coord lon="-0.12574" lat="51.50853"/>
      <country>GB</country>
      <sun rise="2013-10-08T06:13:56" set="2013-10-08T17:21:45"/>
   </city>
   
   <temperature value="289.54" min="289.15" max="290.15" unit="kelvin"/>
   <humidity value="77" unit="%"/>
   <pressure value="1025" unit="hPa"/>

</current>

   
使拉解析器和访问xml文件的功能

  public void fetchXML(){
    Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {
            try {
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();

                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.connect();

                InputStream stream = conn.getInputStream();
                xmlFactoryObject = XmlPullParserFactory.newInstance();
                XmlPullParser myparser = xmlFactoryObject.newPullParser();

                myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                myparser.setInput(stream, null);

                parseXMLAndStoreIt(myparser);
                stream.close();

            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    thread.start();
}

0 个答案:

没有答案