Android,java,xml,xml讀取與儲存,基於AndroidXML解析與儲存的實現

curiousby發表於2014-04-10

獲取XML檔案的基本思路是,通過getResources().getXml()獲的XML原始檔案,得到XmlResourceParser物件,通過該物件來判斷是文件的開頭還是結尾,是某個標籤的開始還是結尾,並通過一些獲取屬性的方法來遍歷XML檔案,從而訪問XML檔案的內容,下面是一個訪問XML檔案內容的例子,並將內容更顯示在一個TextView上

資料寫入xml:

ReadXMLTest.java

  private String WriteToString() {  
        XmlSerializer serializer = Xml.newSerializer();  
        StringWriter writer = new StringWriter();  
        try {  
            serializer.setOutput(writer);  
            serializer.startDocument("utf-8", true);  
            serializer.startTag("", "users");  
  
            serializer.startTag("", "userName");  
            serializer.text(txtUser.getText().toString());  
            serializer.endTag("", "userName");  
  
            serializer.startTag("", "userEmail");  
            serializer.text(txtEmail.getText().toString());  
            serializer.endTag("", "userEmail");  
  
            serializer.startTag("", "passWord");  
            serializer.text(txtPass.getText().toString());  
            serializer.endTag("", "passWord");  
  
            serializer.endTag("", "users");  
            serializer.endDocument();  
  
        } catch (IllegalArgumentException e) {  
            // TODO: handle exception  
            e.printStackTrace();  
        } catch (IllegalStateException e) {  
            // TODO: handle exception  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO: handle exception  
            e.printStackTrace();  
        }  
        return writer.toString();  
    }  
  
    //將字串儲存為apk的私有檔案  
    private boolean writeToXml(String str) {  
        try {  
  
            OutputStream out = openFileOutput("users.xml",MODE_PRIVATE);  
            OutputStreamWriter outWriter = new OutputStreamWriter(out);  
            try {  
                outWriter.write(str);  
                outWriter.close();  
                out.close();  
                return true;  
            } catch (IOException e) {  
                // TODO: handle exception  
                return false;  
            }  
        } catch (Exception e) {  
            // TODO: handle exception  
            return false;  
        }  
    }  

 

呼叫時:

if(writeToXml(WriteToString()))

{

      //成功

}

資料讀取 xml:

private String ReadXmlUser(String tag)  
    {  
        String re="";  
        DocumentBuilderFactory documentBuilderFactory;  
        DocumentBuilder documentBuilder;  
        Document document;  
        try {  
            documentBuilderFactory=DocumentBuilderFactory.newInstance();  
            documentBuilder=documentBuilderFactory.newDocumentBuilder();  
            //xml檔案放到assets目錄下  
            document=documentBuilder.parse(this.openFileInput("users.xml"));  
            org.w3c.dom.Element root= document.getDocumentElement();  
            NodeList nodeList=root.getElementsByTagName(tag);  
            Node nd=nodeList.item(0);  
            re= nd.getFirstChild().getNodeValue();  
        } catch (Exception e) {  
            // TODO: handle exception  
            e.printStackTrace();  
        }finally{  
            document=null;  
            documentBuilder=null;  
            documentBuilderFactory=null;  
        }  
        return re;  
    }  

 

 

 

以上轉載於 http://blog.csdn.net/hanjingjingpan/article/details/8812770 

 

 

 

 

 順便介紹三種xml解析

XML三種常用的解析方式

public class MainActivity extends Activity implements OnClickListener {  
  
    private static final String TAG = "MainActivity";  
  
    Button Sax_praseXml, Dom_praseXml, Pull_praseXml, Write_xml;  
  
    TextView Sax_contentXml, Dom_contentXml, Pull_contentXml;  
  
    String xmlContent;  
  
    MyHandler myhandler;  
  
    List<PersonDetail> list;  
  
    InputStream inputStream;  
  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        xmlContent = "";  
        Sax_praseXml = (Button) findViewById(R.id.btn_sax);  
        Dom_praseXml = (Button) findViewById(R.id.btn_dom);  
        Pull_praseXml = (Button) findViewById(R.id.btn_pull);  
        Sax_contentXml = (TextView) findViewById(R.id.view_sax);  
        Dom_contentXml = (TextView) findViewById(R.id.prase_dom);  
        Pull_contentXml = (TextView) findViewById(R.id.prase_pull);  
        Sax_praseXml.setOnClickListener(this);  
        Dom_praseXml.setOnClickListener(this);  
        Pull_praseXml.setOnClickListener(this);  
  
    }  
  
    public void onClick(View v) {  
        switch (v.getId()) {  
        case R.id.btn_sax:  
            inputStream = MainActivity.class.getClassLoader()  
                    .getResourceAsStream("test.xml");  
            try {  
                Log.v(TAG, "-------sax");  
                StringBuffer sb = new StringBuffer();  
                list = SAXpraseTransiaction.SaxPrase(inputStream);  
                for (PersonDetail tail : list) {  
                    sb.append(tail.toString() + "
");  
                }  
                Sax_contentXml.setText("SaxResult:" + sb.toString());  
                Log.v(TAG, "" + "----------------------" + sb.toString());  
            } catch (Exception E) {  
                Log.v(TAG, "" + "----------------------解析失敗");  
            }  
            break;  
        case R.id.btn_dom:  
            inputStream = MainActivity.class.getClassLoader()  
                    .getResourceAsStream("test.xml");  
            try {  
                Log.v(TAG, "-------DOM");  
                StringBuffer sbDOM = new StringBuffer();  
                list = DomPraserTransaction.getPraserList(inputStream);  
                for (PersonDetail tail : list) {  
                    sbDOM.append(tail.toString() + "
");  
                }  
                Dom_contentXml.setText("DOMResult:" + sbDOM.toString());  
                Log.v(TAG, "" + "----------------------" + sbDOM.toString());  
            } catch (Exception E) {  
                Log.v(TAG, "" + "----------------------解析失敗");  
            }  
            break;  
        case R.id.btn_pull:  
            inputStream = MainActivity.class.getClassLoader()  
                    .getResourceAsStream("test.xml");  
            try {  
                Log.v(TAG, "-------PULL");  
                StringBuffer sbPULL = new StringBuffer();  
                list = PullPraserTransaction.GetResultList(inputStream);  
                for (PersonDetail tail : list) {  
                    sbPULL.append(tail.toString() + "
");  
                }  
                Pull_contentXml.setText("PULLResult:" + sbPULL.toString());  
                Log.v(TAG, "" + "----------------------" + sbPULL.toString());  
            } catch (Exception E) {  
                Log.v(TAG, "" + "----------------------解析失敗");  
            }  
            break;  
        }  
    }  
  
/**  
 * 實用於檔案比較小的Xml解析,簡單實用 2011/9/29  
 *   
 * @author:1314hwl  
 *   
 */  
public class DomPraserTransaction {  
  
    public static List<PersonDetail> getPraserList(InputStream inputStream) {  
        List<PersonDetail> Resultlist = null;  
        PersonDetail Person = null;  
        XmlPullParser pullpraser = Xml.newPullParser();  
        try {  
            pullpraser.setInput(inputStream, "UTF-8");  
            int eventtype = pullpraser.getEventType();  
            while (eventtype != XmlPullParser.END_DOCUMENT) {  
                switch (eventtype) {  
                case XmlPullParser.START_DOCUMENT:  
                    Resultlist = new ArrayList<PersonDetail>();  
                    break;  
                case XmlPullParser.START_TAG:  
                    if ("person".equals(pullpraser.getName())) {  
                        Person = new PersonDetail();  
                        Person.setId(new Integer(pullpraser  
                                .getAttributeValue(0)));  
                    } else if (Person != null) {  
                        if ("name".equals(pullpraser.getName())) {  
                            Person.setName(pullpraser.nextText());  
                        } else if ("age".equals(pullpraser.getName())) {  
                            Person.setAge(new String(pullpraser.nextText()));  
                        }  
                    }  
                    break;  
                case XmlPullParser.END_TAG:  
                    if ("person".equals(pullpraser.getName()) && Person != null) {  
                        Resultlist.add(Person);  
                        Person = null;  
                    }  
                    break;  
                }  
                eventtype = pullpraser.next();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        try {  
            inputStream.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return Resultlist;  
  
    }  
}  
  
/**  
 * pull解析XML pull寫入XML  
 *   
 * @author 1314hwl 2011/9/29  
 *   
 */  
  
public class PullPraserTransaction {  
  
    public static List<PersonDetail> GetResultList(InputStream inputStream)  
            throws Exception {  
  
        List<PersonDetail> Resultlist = new ArrayList<PersonDetail>();  
  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
  
        DocumentBuilder builder = factory.newDocumentBuilder();  
  
        Document document = builder.parse(inputStream);  
  
        Element element = document.getDocumentElement();  
  
        NodeList nodes = element.getElementsByTagName("person");  
  
        int len = nodes.getLength();  
  
        for (int i = 0; i < len; i++) {  
            Element personElement = (Element) nodes.item(i);  
            PersonDetail person = new PersonDetail();  
            person.setId(new Integer(personElement.getAttribute("id")));  
            NodeList childNodes = personElement.getChildNodes();  
            for (int y = 0; y < childNodes.getLength(); y++) {  
                Node childNode = (Node) childNodes.item(y);  
                if (childNode.getNodeType() == Node.ELEMENT_NODE) {  
                    Element childElement = (Element) childNode;  
                    if ("name".equals(childElement.getNodeName())) {  
                        person.setName(childElement.getFirstChild()  
                                .getNodeValue());  
                    }  
                    if ("age".equals(childElement.getNodeName())) {  
                        person.setAge(childElement.getFirstChild()  
                                .getNodeValue());  
                    }  
                }  
            }  
            Resultlist.add(person);  
        }  
        inputStream.close();  
        return Resultlist;  
    }  
}  
  
/**  
 * @author 1314hwl SAX解析 2011/9/29  
 */  
public class SAXpraseTransiaction {  
  
    public static List<PersonDetail> SaxPrase(InputStream inputStream) {  
  
        SAXParserFactory factory = SAXParserFactory.newInstance();//解析工廠  
        // try {  
        // SAXParser saxparser=factory.newSAXParser(); //解析器物件  
        //  
        // MyHandler myhandler=new MyHandler();  
        //  
        // saxparser.parse(inputStream, myhandler);    
        //  
        // inputStream.close();  
        // } catch (Exception e) {  
        //  
        // } 這裡兩種方式:SAXParser or XMLReader 都可以  
        MyHandler myhandler = new MyHandler();  
        try {  
  
            XMLReader xmlreader = factory.newSAXParser().getXMLReader();//實現一個XMLReader  
            xmlreader.setContentHandler(myhandler); //defualthandler  
            xmlreader.parse(new InputSource(inputStream));//要解析的流加入解析中  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        try {  
            inputStream.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return myhandler.resultList();  
  
    }  
  
}  
  
**  
 * SAX解析的defaultHandler  
 *   
 * @author 1314hwl 2011/9/29  
 */  
public class MyHandler extends DefaultHandler {  
    private static final String TAG = "MyHandler";  
    String name, age;  
    String tagname;  
    PersonDetail Person;  
    List<PersonDetail> personList = null;  
  
    public MyHandler() {  
        super();  
        personList = new ArrayList<PersonDetail>();  
    }  
  
    public void characters(char[] ch, int start, int length)  
            throws SAXException {  
        super.characters(ch, start, length);  
        if (Person != null) {  
            String content = new String(ch, start, length);  
            if ("name".equals(tagname)) {  
                Person.setName(content);  
            } else if ("age".equals(tagname)) {  
                Person.setAge(content);  
            }  
        }  
    }  
  
    public void endDocument() throws SAXException {  
        super.endDocument();  
        Log.v(TAG, "解析結束");  
    }  
  
    public void endElement(String uri, String localName, String qName)  
            throws SAXException {  
        super.endElement(uri, localName, qName);  
        if (localName.equals("person") && Person != null) {  
            personList.add(Person);  
            Person = null;  
        }  
        tagname=null;  
    }  
  
    public void startDocument() throws SAXException {  
        super.startDocument();  
        Log.v(TAG, "解析開始");  
  
    }  
  
    public void startElement(String uri, String localName, String qName,  
            Attributes attributes) throws SAXException {  
        super.startElement(uri, localName, qName, attributes);  
        Log.v("startElement", localName);  
        tagname = localName;  
        if (localName.equals("person")) {  
            Person = new PersonDetail();  
            Person.setId(new Integer(attributes.getValue(0)));  
        }  
  
      
    }  
  
    public List<PersonDetail> resultList() {  
        return personList;  
    }  
  
}  
  
public class PersonDetail {  
    String name, age;  
  
    int id;  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    public PersonDetail(int id, String name, String age) {  
        super();  
        this.id = id;  
        this.name = name;  
        this.age = age;  
    }  
  
    public PersonDetail() {  
        super();  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public String getAge() {  
        return age;  
    }  
  
    public void setAge(String age) {  
        this.age = age;  
    }  
  
    public String toString() {  
        return "person [id=" + id + ", name=" + name + ", age=" + age + "]";  
    }  
  
}  

 

 

 

 

以上轉載於  http://blog.csdn.net/hwl1314/article/details/6835493#1536434-tsina-1-56553-66a1f5d8f89e9ad52626f6f40fdeadaa

 

 

 

 

以及 詳解Java反射機制例項

 

 

 

 

import java.lang.reflect.*;     
    
public class ReflectTester {     
    public Object copy(Object object) throws Exception {     
        // 獲得物件的型別     
        Class classType = object.getClass();     
        System.out.println("Class:" + classType.getName());     
        // 通過預設構造方法建立一個新的物件     
        Object objectCopy = classType.getConstructor(new Class[] {})     
                .newInstance(new Object[] {});     
        // 獲得物件的所有屬性     
        Field fields[] = classType.getDeclaredFields();     
        for (int i = 0; i < fields.length; i++) {     
            Field field = fields[i];     
            String fieldName = field.getName();     
            String firstLetter = fieldName.substring(0, 1).toUpperCase();     
            // 獲得和屬性對應的getXXX()方法的名字     
            String getMethodName = "get" + firstLetter + fieldName.substring(1);     
            // 獲得和屬性對應的setXXX()方法的名字     
            String setMethodName = "set" + firstLetter + fieldName.substring(1);     
            // 獲得和屬性對應的getXXX()方法     
            Method getMethod = classType.getMethod(getMethodName,     
                    new Class[] {});     
            // 獲得和屬性對應的setXXX()方法     
            Method setMethod = classType.getMethod(setMethodName,     
                    new Class[] { field.getType() });     
            // 呼叫原物件的getXXX()方法     
            Object value = getMethod.invoke(object, new Object[] {});     
            System.out.println(fieldName + ":" + value);     
            // 呼叫複製物件的setXXX()方法     
            setMethod.invoke(objectCopy, new Object[] { value });     
        }     
        return objectCopy;     
    }     
    
    public static void main(String[] args) throws Exception {     
        Customer customer = new Customer("Tom", 21);     
        customer.setId(new Long(1));     
        Customer customerCopy = (Customer) new ReflectTester().copy(customer);     
        System.out.println("Copy information:" + customerCopy.getName() + " "    
                + customerCopy.getAge());     
    }     
}     
    
class Customer { // Customer類是一個JavaBean     
    private Long id;     
    private String name;     
    private int age;     
    
    public Customer() {     
    }     
    
    public Customer(String name, int age) {     
        this.name = name;     
        this.age = age;     
    }     
    
    public Long getId() {     
        return id;     
    }     
    
    public void setId(Long id) {     
        this.id = id;     
    }     
    
    public String getName() {     
        return name;     
    }     
    
    public void setName(String name) {     
        this.name = name;     
    }     
    
    public int getAge() {     
        return age;     
    }     
    
    public void setAge(int age) {     
        this.age = age;     
    }     
}   

 

 

 

 

 

反射轉載於 http://developer.51cto.com/art/201103/248118.htm#585532-tsina-1-63092-7e393678b940a4d55500bf3feae3d2e9

 

 

 

 

 

 

 

 

 

 閱讀完以上的內容

 

我們的第一個方法 WriteToString() 就可以通過反射直接寫出,不需要每次都寫好多屬性

舉例說明:Product.Java

 

 

 

 

 

 

 

 

private String name;
	private String price;
	
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPrice() {
		return price;
	}
	public void setPrice(String price) {
		this.price = price;
	}

 

 Test.java

 

 

 

 

 

 

 

 

 

public static void main(String[] args) throws Exception  {
	
	List<Product> plist = new ArrayList<Product>();
	Product p1=  new Product();
	p1.setName("空氣淨化器1");
	p1.setPrice("3799");
	plist.add(p1);
	
	Product p2=  new Product();
	p2.setName("空氣淨化器2");
	p2.setPrice("3799");
	plist.add(p2);
	
	produceXml(Product.class , plist);
}
public static String produceXml(Class clazz,List plist) throws Exception{
	 System.out.println("<" +clazz.getName().toLowerCase()+"s" +">");
	 
	 for(Object o:plist){  
		 System.out.println( "<" +clazz.getName().toLowerCase()+">");
	 for(int i=0;i< clazz.getDeclaredFields().length;i++){
		 System.out.print("<" + clazz.getDeclaredFields()[i].getName() +">");  
        
            for(int j = 0; j < Product.class.getDeclaredMethods().length; j++) {
         	  if (  ("get"+clazz.getDeclaredFields()[i].getName().substring(0,1).toUpperCase()+( clazz.getDeclaredFields()[i].getName().substring(1)) ).equals( clazz.getDeclaredMethods()[j].getName() )){
         		
         		  Method getMethod = clazz.getMethod(clazz.getDeclaredMethods()[j].getName(),  new Class[]{});
         		 Object result = getMethod.invoke( o, new Object[] {}); 
         		 System.out.print( result.toString());
	                }
       	   }
         
         System.out.println("</"+ clazz.getDeclaredFields()[i].getName() +">"); 	
    	
      }
	 System.out.println( "</"+clazz.getName().toLowerCase()+">");
	 }
	 
	 System.out.println( "</"+clazz.getName().toLowerCase()+"s"+">");
	 return null;
 }

 

執行結果:

<products>
<product>
<name>空氣淨化器1</name>
<price>3799</price>
</product>
<product>
<name>空氣淨化器2</name>
<price>3799</price>
</product>
</products>

 

System.out.println( “</”+  ……+”>”); 替換成xmlSerializer.endTag(null, ……);就ok了哦!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助開發者

在興趣的驅動下,寫一個免費的東西,有欣喜,也還有汗水,希望你喜歡我的作品,同時也能支援一下。 當然,有錢捧個錢場(右上角的愛心標誌,支援支付寶和PayPal捐助),沒錢捧個人場,謝謝各位。


 
 
 謝謝您的贊助,我會做的更好!

 

 


相關文章