Android项目中解析XML文件的方法有哪些-成都快上网建站

Android项目中解析XML文件的方法有哪些

今天就跟大家聊聊有关Android项目中解析XML文件的方法有哪些,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

博兴网站建设公司创新互联公司,博兴网站设计制作,有大型网站制作公司丰富经验。已为博兴上千提供企业网站建设服务。企业网站搭建\外贸网站建设要多少钱,请找那个售后服务好的博兴做网站的公司定做!

1.xml文件代码

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page isELIgnored="false" %>


      
        ${fq.content}
        
      
  

2.XML网页效果图

Android项目中解析XML文件的方法有哪些

3.Android代码

1.布局文件

<?xml version="1.0" encoding="utf-8"?>


  

2.java代码

DOM解析代码

public class MainActivity extends AppCompatActivity {

  private ListView lv_main_list;
  private ProgressDialog progressDialog;
  private List fqs = new ArrayList<>();
  private MyAdapter myadapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv_main_list = (ListView) findViewById(R.id.lv_main_list);

    myadapter = new MyAdapter();
    lv_main_list.setAdapter(myadapter);

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("小青正在拼命加載中.....");
  }

  class MyAdapter extends BaseAdapter{

    @Override
    public int getCount() {
      return fqs.size();
    }

    @Override
    public Object getItem(int position) {
      return fqs.get(position);
    }

    @Override
    public long getItemId(int position) {
      return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      if(convertView==null){
        convertView=LayoutInflater.from(MainActivity.this).inflate(R.layout.item_list,null);
        ItemTag itemTag=new ItemTag();
        itemTag.tv_name= (TextView) convertView.findViewById(R.id.tv_item_listview_name);
        itemTag.tv_content= (TextView) convertView.findViewById(R.id.tv_item_listview_content);
        itemTag.tv_tiem= (TextView) convertView.findViewById(R.id.tv_item_listview_time);
        convertView.setTag(itemTag);
      }
      ItemTag itemTag= (ItemTag) convertView.getTag();
      itemTag.tv_name.setText(fqs.get(position).getName());
      itemTag.tv_content.setText(fqs.get(position).getContent());
      itemTag.tv_tiem.setText(fqs.get(position).getTime());

      return convertView;
    }
  }

  public void getXML(View view) {
    new MyTask().execute();
  }

  class MyTask extends AsyncTask {
    //获取数据前
    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      progressDialog.show();
    }

    @Override
    protected Object doInBackground(Object[] params) {
      //获取网络数据
      //1.定义获取网络的数据的路径
      String path = "http://192.168.43.149:8080/dataResult.xhtml";
      //2.实例化URL
      try {
        URL url = new URL(path);
        //3.获取链接对象
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        //4.设置请求
        httpURLConnection.setRequestMethod("GET");
        //5.设置请求链接超时的时间
        httpURLConnection.setConnectTimeout(5000);
        //6.获取响应码
        int code = httpURLConnection.getResponseCode();
        if (code == 200) {
          //7.获取返回过来的数据(XML)
          InputStream is = httpURLConnection.getInputStream();
          //8.使用DOM解析XML文件
          DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
          DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
          Document document=documentBuilder.parse(is);
          //获取根标签
          Element root=document.getDocumentElement();
          NodeList nodeList = root.getElementsByTagName("fq");
          for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            //获取属性name
            String name = element.getAttribute("name");
            //获取子标签content,time
            Element elementContent = (Element) element.getElementsByTagName("content").item(0);
            String content = elementContent.getTextContent();
            Element elementTime = (Element) element.getElementsByTagName("time").item(0);
            String time = elementTime.getTextContent();
            FQ fq = new FQ(name, content, time);
            fqs.add(fq);
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      return fqs;
    }

    //获取数据后更新UI
    @Override
    protected void onPostExecute(Object o) {
      super.onPostExecute(o);
      progressDialog.cancel();
      myadapter.notifyDataSetChanged();
    }
  }
}

PULL解析代码

public class MainPullActivity extends AppCompatActivity {

  private ListView lv_mainpull_list;
  private ProgressDialog progressDialog;
  private List fqs = new ArrayList<>();
  private MyAdapter myadapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_pull);
    myadapter = new MyAdapter();
    lv_mainpull_list = (ListView) findViewById(R.id.lv_mainpull_list);
    lv_mainpull_list.setAdapter(myadapter);

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("小青正在拼命加載中.....");
  }

  class MyAdapter extends BaseAdapter {

    @Override
    public int getCount() {
      return fqs.size();
    }

    @Override
    public Object getItem(int position) {
      return fqs.get(position);
    }

    @Override
    public long getItemId(int position) {
      return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      if (convertView == null) {
        convertView = LayoutInflater.from(MainPullActivity.this).inflate(R.layout.item_list, null);
        ItemTag itemTag = new ItemTag();
        itemTag.tv_name = (TextView) convertView.findViewById(R.id.tv_item_listview_name);
        itemTag.tv_content = (TextView) convertView.findViewById(R.id.tv_item_listview_content);
        itemTag.tv_tiem = (TextView) convertView.findViewById(R.id.tv_item_listview_time);
        convertView.setTag(itemTag);
      }
      ItemTag itemTag = (ItemTag) convertView.getTag();
      itemTag.tv_name.setText(fqs.get(position).getName());
      itemTag.tv_content.setText(fqs.get(position).getContent());
      itemTag.tv_tiem.setText(fqs.get(position).getTime());

      return convertView;
    }
  }

  public void getPULL(View view) {
    new MyTask().execute();
  }

  class MyTask extends AsyncTask {
    private FQ fq;

    //获取数据前
    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      progressDialog.show();
    }

    @Override
    protected Object doInBackground(Object[] params) {
      //获取网络数据
      //1.定义获取网络的数据的路径
      String path = "http://192.168.43.149:8080/dataResult.xhtml";
      //2.实例化URL
      try {
        URL url = new URL(path);
        //3.获取链接对象
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        //4.设置请求
        httpURLConnection.setRequestMethod("GET");
        //5.设置请求链接超时的时间
        httpURLConnection.setConnectTimeout(5000);
        //6.获取响应码
        int code = httpURLConnection.getResponseCode();
        if (code == 200) {
          //7.获取返回过来的数据(XML)
          InputStream is = httpURLConnection.getInputStream();
          //8.解析XML
          //使用PULL解析XML文件
          XmlPullParser pullParser= Xml.newPullParser();
          pullParser.setInput(is,"UTF-8");
          int type=pullParser.getEventType();
          while (type!=XmlPullParser.END_DOCUMENT){
            switch (type){
              case XmlPullParser.START_TAG:
                //获取开始标签名字
                String startTafName=pullParser.getName();
                 if("fq".equals(startTafName)){
                   fq = new FQ();
                   String name=pullParser.getAttributeValue(0);
                   fq.setName(name);
                 }else if ("content".equals(startTafName)){
                   String content=pullParser.nextText();
                   fq.setContent(content);
                 }else if ("time".equals(startTafName)){
                   String time=pullParser.nextText();
                   fq.setTime(time);
                 }
                break;
              case XmlPullParser.END_TAG:
                //获取接受标签的名字
                String endtagname=pullParser.getName();
                if("fq".equals(endtagname)){
                  fqs.add(fq);
                }
                break;
            }
            type=pullParser.next();
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      return fqs;
    }

    //获取数据后更新UI
    @Override
    protected void onPostExecute(Object o) {
      super.onPostExecute(o);
      progressDialog.cancel();
      myadapter.notifyDataSetChanged();
    }
  }
}

SAX解析代码

public class MainSaxActivity extends AppCompatActivity {

  private ListView lv_mainsax_list;
  private ProgressDialog progressDialog;
  private List fqs = new ArrayList<>();
  private MyAdapter myadapter;
  private String currentTag = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_sax);
    lv_mainsax_list = (ListView) findViewById(R.id.lv_mainsax_list);
    myadapter = new MyAdapter();
    lv_mainsax_list.setAdapter(myadapter);

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("小青正在拼命加載中.....");
  }

  class MyAdapter extends BaseAdapter {

    @Override
    public int getCount() {
      return fqs.size();
    }

    @Override
    public Object getItem(int position) {
      return fqs.get(position);
    }

    @Override
    public long getItemId(int position) {
      return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      if (convertView == null) {
        convertView = LayoutInflater.from(MainSaxActivity.this).inflate(R.layout.item_list, null);
        ItemTag itemTag = new ItemTag();
        itemTag.tv_name = (TextView) convertView.findViewById(R.id.tv_item_listview_name);
        itemTag.tv_content = (TextView) convertView.findViewById(R.id.tv_item_listview_content);
        itemTag.tv_tiem = (TextView) convertView.findViewById(R.id.tv_item_listview_time);
        convertView.setTag(itemTag);
      }
      ItemTag itemTag = (ItemTag) convertView.getTag();
      itemTag.tv_name.setText(fqs.get(position).getName());
      itemTag.tv_content.setText(fqs.get(position).getContent());
      itemTag.tv_tiem.setText(fqs.get(position).getTime());

      return convertView;
    }
  }

  public void getSAX(View view) {
    new MyTask().execute();
  }

  class MyTask extends AsyncTask {

    private FQ fq;

    //获取数据前
    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      progressDialog.show();
    }

    @Override
    protected Object doInBackground(Object[] params) {
      //获取网络数据
      //1.定义获取网络的数据的路径
      String path = "http://192.168.43.149:8080/dataResult.xhtml";
      //2.实例化URL
      try {
        URL url = new URL(path);
        //3.获取链接对象
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        //4.设置请求
        httpURLConnection.setRequestMethod("GET");
        //5.设置请求链接超时的时间
        httpURLConnection.setConnectTimeout(5000);
        //6.获取响应码
        int code = httpURLConnection.getResponseCode();
        if (code == 200) {
          //7.获取返回过来的数据(XML)
          InputStream is = httpURLConnection.getInputStream();
          //8.解析XML
          //使用SAX解析XML文件
          SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
          SAXParser saxParser = saxParserFactory.newSAXParser();
          saxParser.parse(is, new DefaultHandler() {
            @Override
            public void startDocument() throws SAXException {
              super.startDocument();
            }

            @Override
            public void endDocument() throws SAXException {
              super.endDocument();
            }

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
              super.startElement(uri, localName, qName, attributes);
              currentTag = localName;
              if ("fq".equals(localName)) {
                //实例化对象
                fq = new FQ();
                String name = attributes.getValue(0);
                fq.setName(name);
              }
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
              super.endElement(uri, localName, qName);
              currentTag=null;
              if ("fq".equals(localName)){
                fqs.add(fq);
              }
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
              super.characters(ch, start, length);
              if ("content".equals(currentTag)) {
                String content = new String(ch, start, length);
                fq.setContent(content);
              }else if ("time".equals(currentTag)) {
                String time = new String(ch, start, length);
                fq.setTime(time);
              }
            }
          });
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      return fqs;
    }

    //获取数据后更新UI
    @Override
    protected void onPostExecute(Object o) {
      super.onPostExecute(o);
      progressDialog.cancel();
      myadapter.notifyDataSetChanged();
    }
  }
}

实体类

public class FQ {
  private String name;
  private String content;
  private String time;

  public FQ(){}
  public FQ(String name, String time, String content) {
    this.name = name;
    this.time = time;
    this.content = content;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getContent() {
    return content;
  }

  public void setContent(String content) {
    this.content = content;
  }

  public String getTime() {
    return time;
  }

  public void setTime(String time) {
    this.time = time;
  }
}

public class ItemTag {
  public TextView tv_name;
  public TextView tv_content;
  public TextView tv_tiem;
}

配置文件添加联网权限


看完上述内容,你们对Android项目中解析XML文件的方法有哪些有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


新闻名称:Android项目中解析XML文件的方法有哪些
URL网址:http://kswjz.com/article/pceeds.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流