Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> andriod讀寫XML,andriodxml

andriod讀寫XML,andriodxml

編輯:關於android開發

andriod讀寫XML,andriodxml


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yanlei.wifi" >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- 在SDCard中創建與刪除文件權限 -->

    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

    <!-- 連接<a href="http://www.it165.net/news/nhlw/" target="_blank" class="keylink">互聯網</a>Internet權限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- GPS定位權限 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
        android:id="@+id/btn1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="創建XML文件"
        />
    <Button
        android:id="@+id/btn2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="DOM解析XML"
        />

    <TextView
        android:id="@+id/result"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>
package com.example.yanlei.wifi;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String BOOKS_PATH = "/sdcard/books.xml";
    private View mButton1,mButton2,mButton3;
    private TextView mTextView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupViews();
    }
    //初始化工作
    private void setupViews(){
        mTextView = (TextView)findViewById(R.id.result);
        mButton1 = (View)findViewById(R.id.btn1);
        mButton2 = (View)findViewById(R.id.btn2);

        mButton1.setOnClickListener(new Button1ClickListener());
        mButton2.setOnClickListener(new Button2ClickListener());

    }
    private class Button1ClickListener implements View.OnClickListener {

        public void onClick(View v) {
            createXmlFile();
        }
    }
    private class Button2ClickListener implements View.OnClickListener {

        public void onClick(View v) {
            domParseXML();
        }
    }

    //創建xml文件
    private void createXmlFile(){
        File linceseFile = new File(BOOKS_PATH);
        try{
            linceseFile.createNewFile();
        }catch (IOException e) {
            Log.e("IOException", "exception in createNewFile() method");
        }
        FileOutputStream fileos = null;
        try{
            fileos = new FileOutputStream(linceseFile);
        }catch (FileNotFoundException  e) {
            Log.e("FileNotFoundException", "can't create FileOutputStream");
        }
        XmlSerializer serializer = Xml.newSerializer();
        try {
            serializer.setOutput(fileos,"UTF-8");
            serializer.startDocument(null, true);
            serializer.startTag(null, "books");
            for(int i = 0; i < 3; i ++){
                serializer.startTag(null, "book");
                serializer.startTag(null, "bookname");
                serializer.text("Android教程" + i);
                serializer.endTag(null, "bookname");
                serializer.startTag(null, "bookauthor");
                serializer.text("Frankie" + i);
                serializer.endTag(null, "bookauthor");
                serializer.endTag(null, "book");
            }

            serializer.endTag(null, "books");
            serializer.endDocument();
            serializer.flush();
            fileos.close();
        } catch (Exception e) {
            Log.e("Exception","error occurred while creating xml file");
        }
        Toast.makeText(getApplicationContext(), "創建xml文件成功!", Toast.LENGTH_SHORT).show();
    }
    //dom解析xml文件
    private void domParseXML(){
        File file = new File(BOOKS_PATH);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = null;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document doc = null;
        try {
            doc = db.parse(file);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Element root = doc.getDocumentElement();
        NodeList books = root.getElementsByTagName("book");
        String res = "本結果是通過dom解析:" + "/n";
        for(int i = 0; i < books.getLength();i++){
            Element book = (Element)books.item(i);
            Element bookname = (Element)book.getElementsByTagName("bookname").item(0);
            Element bookauthor = (Element)book.getElementsByTagName("bookauthor").item(0);
            res += "書名: " + bookname.getFirstChild().getNodeValue() + " " +
                    "作者: " + bookauthor.getFirstChild().getNodeValue() + "/n";
        }

        mTextView.setText(res);
    }





    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved