Home Backend Development XML/RSS Tutorial Summary of three methods of operating XML in Android

Summary of three methods of operating XML in Android

Apr 21, 2017 pm 05:13 PM
android xml

In Android, there are generally several ways to operate xml files: SAX operation, Pull operation, DOM operation, etc. Among them, the DOM method may be the most familiar to everyone, and it is also in line with the W3C standard. As an industry-recognized data exchange format, XML is available on various platforms and languages. Widely used and implemented. Its standard type, reliability, safety... There is no doubt about it. On the Android platform, if we want to implement data storage and data exchange, we often use xml data format and xml files.

Tips:

The data stored in android generally includes the following types: SharedPreferences (parameterized), XML file, sqllite database, network, ContentProvider (content provider), etc. In Android, there are generally several ways to operate xml files: SAX operation, Pull operation, DOM operation, etc. Among them, the DOM method may be the most familiar to everyone, and it is also in line with W3C standards.

1)In the Java platform, there are excellent open source packages such as DOM4J, which greatly facilitates everyone’s use of the DOM standard. Manipulate XML files. In JavaScript, different browser parsing engines have slightly different parsing and operations on DOM (but this is not the focus of this chapter). The DOM method also has its shortcomings. Usually, the xml file is loaded once and then parsed using DOM's

api

. This consumes a lot of memory and has a certain impact on performance. Although the configuration of our Android phones is constantly being upgraded, in terms of memory, it is still unable to compete with traditional PCs. Therefore, on Android, it is not recommended to use DOM to parse and operate XML.

Copy code

The code is as follows:

package cn.itcast.service;
import java.io.InputStream;import java.util.ArrayList;import java.util.List;
import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;
import cn.itcast.model.Person;
public class DomPersonService {
  public List<Person> getPersons(InputStream stream) throws Throwable
  {
   List<Person> list =new ArrayList<Person>();
   DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
   DocumentBuilder builder =factory.newDocumentBuilder();
   Document dom = builder.parse(stream);//解析完成,并以dom树的方式存放在内存中。比较消耗性能
   //开始使用dom的api去解析
   Element root = dom.getDocumentElement();//根元素
    NodeList personNodes = root.getElementsByTagName("person");//返回所有的person元素节点
  //开始遍历啦
  for(int i=0;i<personNodes.getLength();i++)
  {
   Person person =new Person();
  Element personElement =(Element)personNodes.item(i);
    person.setId(new Integer( personElement.getAttribute("id")));//将person元素节点的属性节点id的值,赋给person对象
    NodeList personChildrenNodes =personElement.getChildNodes();//获取person节点的所有子节点
    //遍历所有子节点
    for(int j=0;j<personChildrenNodes.getLength();j++)
    {
     //判断子节点是否是元素节点(如果是文本节点,可能是空白文本,不处理)
     if(personChildrenNodes.item(j).getNodeType()==Node.ELEMENT_NODE)
     { 
      //子节点--元素节点
      Element childNode =(Element)personChildrenNodes.item(j);
           if("name".equals(childNode.getNodeName()))
         {
          //如果子节点的名称是“name”.将子元素节点的第一个子节点的值赋给person对象
           person.setName(childNode.getFirstChild().getNodeValue());
          }else if("age".equals(childNode.getNodeValue()))
         {
           person.setAge(new Integer(childNode.getFirstChild().getNodeValue()));
         }
     }
    }
    list.add(person);
  }
  return list;
  }}
Copy after login

##2)
SAX (Simple API for XML) is a very widely used XML parsing standard. Handler mode is usually used to process XML documents. This processing mode is very different from the way we are usually used to understanding it. There are often some friends around who are new to it. When using SAX, you may find it a little difficult to understand. In fact, SAX is not complicated, it is just a different way of thinking. As its name indicates, in order to allow us to process XML documents in a simpler way, let's get started.


Copy code

The code is as follows:

package cn.itcast.service;
import java.io.InputStream;import java.util.ArrayList;import java.util.List;
import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;
import cn.itcast.model.Person;
public class SAXPersonService {   public List<Person> getPersons(InputStream inStream) throws Throwable
   {
    SAXParserFactory factory = SAXParserFactory.newInstance();//工厂模式还是单例模式?
    SAXParser parser =factory.newSAXParser();
    PersonParse personParser =new PersonParse();
    parser.parse(inStream, personParser);
    inStream.close();
    return personParser.getPerson();
   }
   private final class PersonParse extends DefaultHandler
   {  private List<Person> list = null;
    Person person =null;
    private String tag=null;
    public List<Person> getPerson()
     {
       return list;
        }
    @Override public void startDocument() throws SAXException
     {
      list =new ArrayList<Person>();
      }
 @Override public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {
  if("person".equals(localName))
  {
   //xml元素节点开始时触发,是“person”
   person = new Person();
   person.setId(new Integer(attributes.getValue(0)));
  }
  tag =localName;//保存元素节点名称 } @Override public void endElement(String uri, String localName, String qName)
   throws SAXException {
  //元素节点结束时触发,是“person”
  if("person".equals(localName))
  {
   list.add(person);
   person=null;
  }
  tag =null;//结束时,需要清空tag
  } @Override public void characters(char[] ch, int start, int length)
   throws SAXException {  if(tag!=null)
  {
   String data = new String(ch,start,length);
     if("name".equals(tag))
     {
     person.setName(data);
     }else if("age".equals(tag))
     {
       person.setAge(new Integer(data));
       }
     }
    }
  }
}
Copy after login

##3)


Pull parsing is very similar to Sax parsing. They are both lightweight parsing. Pull has been embedded in the Android kernel, so we do not need to add a third-party jar package to support Pull. The differences between Pull parsing and Sax parsing are (1) pull triggers the corresponding event after reading the xml file The calling method returns a number (2) pull can control where it wants to parse in the program Stop parsing.

Copy code
The code is as follows:

package cn.itcast.service;
import java.io.InputStream;import java.io.Writer;import java.util.ArrayList;import java.util.List;
import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlSerializer;
import android.util.Xml;
import cn.itcast.model.Person;
public class PullPersonService { //保存xml文件 public static void saveXML(List<Person> list,Writer write)throws Throwable
 {  XmlSerializer serializer =Xml.newSerializer();//序列化
 serializer.setOutput(write);//输出流
 serializer.startDocument("UTF-8", true);//开始文档
 serializer.startTag(null, "persons");
   //循环去添加person
  for (Person person : list) {
   serializer.startTag(null, "person");
   serializer.attribute(null, "id", person.getId().toString());//设置id属性及属性值
   serializer.startTag(null, "name");
   serializer.text(person.getName());//文本节点的文本值--name
   serializer.endTag(null, "name");   serializer.startTag(null, "age");
   serializer.text(person.getAge().toString());//文本节点的文本值--age
   serializer.endTag(null, "age");   serializer.endTag(null, "person");
       }
    serializer.endTag(null, "persons");
    serializer.endDocument();
    write.flush();
    write.close(); }
    public List<Person> getPersons(InputStream stream) throws Throwable
      {
       List<Person> list =null;
       Person person =null;
       XmlPullParser parser =Xml.newPullParser();
       parser.setInput(stream,"UTF-8");
     int type =parser.getEventType();//产生第一个事件
       //只要当前事件类型不是”结束文档“,就去循环
       while(type!=XmlPullParser.END_DOCUMENT)
      {
    switch (type) {
    case XmlPullParser.START_DOCUMENT:
    list = new ArrayList<Person>();
    break;
      case XmlPullParser.START_TAG:
    String name=parser.getName();//获取解析器当前指向的元素名称
    if("person".equals(name))
    {
    person =new Person();
    person.setId(new Integer(parser.getAttributeValue(0)));
    }
    if(person!=null)
     {
    if("name".equals(name))
    {
      person.setName(parser.nextText());//获取解析器当前指向的元素的下一个文本节点的文本值
    }
    if("age".equals(name))
    {
     person.setAge(new Integer(parser.nextText()));
    }
   }
   break;
  case XmlPullParser.END_TAG:
   if("person".equals(parser.getName()))
   {
    list.add(person);
    person=null;
   }
     break;
    }
     type=parser.next();//这句千万别忘了哦
     }
   return list;
  }
}
Copy after login

The following is the code of the Person class of the Model layer:


Copy code
The code is as follows:

package cn.itcast.model;
public class Person {private Integer id;public Integer getId() { return id;}public void setId(Integer id) { this.id = id;}
private String name;public String getName() { return name;}
public void setName(String name) { this.name = name;}
private Integer age;public Integer getAge() { return age;}
public void setAge(Integer age) { this.age = age;}
public Person(){}public Person(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age;}
@Overridepublic String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";}
}
Copy after login

The above is the detailed content of Summary of three methods of operating XML in Android. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship Sep 10, 2024 am 06:45 AM

OnePlus'sister brand iQOO has a 2023-4 product cycle that might be nearlyover; nevertheless, the brand has declared that it is not done with itsZ9series just yet. Its final, and possibly highest-end,Turbo+variant has just beenannouncedas predicted. T

See all articles