一、XML解析简介:
XML:Extensible Markup Language,即可扩展标记语言. 用于标记电子文件使其具有结构性的标记语言,可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。非常适合 Web 传输。XML 提供统一的方法来描述和交换独立于应用程序或供应商的结构化数据.
二、DOM:
DOM(Document Object Model) 是一种用于XML文档的对象模型,可用于直接访问 XML 文档的各个部分。它是一次性全部将内容加载在内存中,生成一个树状结构,它没有涉及回调和复杂的状态管理。
缺点是加载大文档时效率低下
XML代码:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<name>冰与火之歌</name>
<author>乔治马丁</author>
<year>2014</year>
<price>89</price>
</book>
<book id="2">
<name>安徒生童话</name>
<author>安徒生</author>
<year>2004</year>
<price>77</price>
</book>
</bookstore>
java代码:
package xml.task.demo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.example.map_demo.R;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class Activity_xml_task extends AppCompatActivity {
ArrayList<BookBean> beans;
private final String TAG = "TAG###";
/**
* 解析为了获得对象、集合
* xml:标记语言,用来网络传输 格式压缩 速度快
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xml_task);
dom();
}
private void dom() {
beans = new ArrayList<>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//获得解析工厂
try {
DocumentBuilder builder = factory.newDocumentBuilder();//创建builder对象
InputStream is = getAssets().open("books.xml");
Document document = builder.parse(is);//这一步是把文件添加到内存中 从内存中拿更快
//接下来跟document玩
NodeList list = document.getElementsByTagName("book");//获取文件中所有节点名为book的内容,并打算将这些内容存入List中去
for(int i = 0;i < list.getLength();i++){
//这样就拿到了一个book对象 也就是一个对象的内容,包括五个属性
BookBean bean = new BookBean();
Node node = list.item(i);//当i等于0时,获得的是第一个book对象
//获得属性
String id = node.getAttributes().getNamedItem("id").getNodeValue();
//获取姓名
String name = node.getAttributes().getNamedItem("name").getNodeValue();
Log.e("name",name);
String year = node.getAttributes().getNamedItem("year").getNodeValue();
String author = node.getAttributes().getNamedItem("author").getNodeValue();
String price = node.getAttributes().getNamedItem("price").getNodeValue();
bean.setId(id);
bean.setAuthor(author);
bean.setName(name);
bean.setPrice(price);
bean.setYear(year);
beans.add(bean);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void Check(){
for (BookBean bookBean:beans) {
Log.e(TAG,bookBean.getId());
Log.e(TAG,bookBean.getName());
Log.e(TAG,bookBean.getPrice());
Log.e(TAG,bookBean.getAuthor());
Log.e(TAG,bookBean.getYear());
}
}
}