andriod读写XML

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了andriod读写XML相关的知识,希望对你有一定的参考价值。

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

 

以上是关于andriod读写XML的主要内容,如果未能解决你的问题,请参考以下文章

Andriod XML Editor cannot process this input

应用程序可能在 Andriod 中的主线程(Firebase 数据库)上做了太多工作

在Tomcat的安装目录下conf目录下的server.xml文件中增加一个xml代码片段,该代码片段中每个属性的含义与用途

Andriod里面的Selector是啥东西,实现啥功能???

andriod设备APP开发之各种细节部署和操作

andriod设备APP开发之数据就地Excel存储