[Android基础]读写xml、json格式的数据

1.读写xml格式的数据

languages.xml(存放在assets文件夹)

<?xml version="1.0" encoding="utf-8"?>
<Languages cat="it">
    <lan id="1">
        <name>Java</name>
        <ide>Eclipse</ide>
    </lan>
    <lan id="2">
        <name>Swift</name>
        <ide>Xcode</ide>
    </lan>
    <lan id="3">
        <name>C#</name>
        <ide>Visual Studio</ide>
    </lan>
</Languages>

package com.example.testxml;

import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView textView;
	private DocumentBuilderFactory builderFactory;
	private DocumentBuilder builder;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView = (TextView)findViewById(R.id.textView);
		try {
			builderFactory = DocumentBuilderFactory.newInstance();
			builder = builderFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e1) {
			e1.printStackTrace();
		}
		
		//ReadXML();
		WriteXML();
	}
	
	private void ReadXML()
	{
		try {
			Document document = builder.parse(getAssets().open("languages.xml"));
			Element element = document.getDocumentElement();
			NodeList list = element.getElementsByTagName("lan");
			for(int i = 0;i < list.getLength();i++) {
				Element lan = (Element)list.item(i);
				textView.append(lan.getAttribute("id") + "\n");
				textView.append(lan.getElementsByTagName("name").item(0).getTextContent() + "\n");
				textView.append(lan.getElementsByTagName("ide").item(0).getTextContent() + "\n");
			}
		} catch (SAXException | IOException e) {
			e.printStackTrace();
		}	
	}
	
	private void WriteXML()
	{
		try {
			Document newxml = builder.newDocument();
			Element languages = newxml.createElement("Languages");
			languages.setAttribute("cat", "it");
			
			Element lan1 = newxml.createElement("lan");
			lan1.setAttribute("id", "1");
			Element name1 = newxml.createElement("name");
			name1.setTextContent("Java");
			Element ide1 = newxml.createElement("ide");
			ide1.setTextContent("Eclipse");
			lan1.appendChild(name1);
			lan1.appendChild(ide1);
			languages.appendChild(lan1);
			
			newxml.appendChild(languages);
			
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty("encoding", "utf-8");
			StringWriter sw = new StringWriter();
			transformer.transform(new DOMSource(newxml), new StreamResult(sw));
			
			textView.setText(sw.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


2.读写json格式的数据

test.json(存放在assets文件夹)

{
	"languages": [
	    {"id":1,"ide":"Eclipse","name":"Java"},
	    {"id":2,"ide":"XCode","name":"Swift"},
	    {"id":3,"ide":"Visual Studio","name":"C#"}
	],
	"cat":"it"
 }

package com.example.testjson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView textView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView = (TextView)findViewById(R.id.textView);
		
		//ReadJSON();
		WriteJSON();
	}
	
	private void ReadJSON()
	{
		try {
			InputStreamReader isr = new InputStreamReader(getAssets().open("test.json"),"UTF-8");
			BufferedReader br = new BufferedReader(isr);
			String line;
			StringBuilder builder = new StringBuilder();
			while ((line = br.readLine()) != null) {
				builder.append(line);
			}
			br.close();
			isr.close();
			
			JSONObject root = new JSONObject(builder.toString());
			textView.append("cat=" + root.getString("cat") + "\n");
			JSONArray array = root.getJSONArray("languages");
			for (int i = 0; i < array.length(); i++) {
				JSONObject lan = array.getJSONObject(i);
				textView.append("-------------" + "\n");
				textView.append("id=" + lan.getInt("id") + "\n");
				textView.append("name=" + lan.getString("name") + "\n");
				textView.append("ide=" + lan.getString("ide") + "\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void WriteJSON()
	{
		try {
			JSONObject root = new JSONObject();
			root.put("cat", "it");
			
			JSONObject lan1 = new JSONObject();
			lan1.put("id", 1);
			lan1.put("ide", "Eclipse");
			lan1.put("name", "Java");
			
			JSONObject lan2 = new JSONObject();
			lan2.put("id", 2);
			lan2.put("ide", "Xcode");
			lan2.put("name", "Swift");
			
			JSONObject lan3 = new JSONObject();
			lan3.put("id", 3);
			lan3.put("ide", "Visual Studio");
			lan3.put("name", "C#");
			
			JSONArray array = new JSONArray();
			array.put(lan1);
			array.put(lan2);
			array.put(lan3);
			
			root.put("languages", array);
			textView.append(root.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值