android学习笔记18:Dom和Dom4j解析XML

来源:互联网 发布:淘宝联盟怎么自己买 编辑:程序博客网 时间:2024/05/21 01:32

1. Dom解析XML:


处理dom解析的核心类

   public class DomService
{

    public DomService()
    {
        // TODO Auto-generated constructor stub
    }

    public List getBooks(InputStream inputStream) throws Exception
    {
        List list = new ArrayList();
        // 创建一个document解析的工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // 获取具体的dom解析器
        DocumentBuilder builder = factory.newDocumentBuilder();
        // 解析xml文件的输入流并返回document对象
        Document document = builder.parse(inputStream);
        // 获取文档根元素节点
        Element root = document.getDocumentElement();
        //获取指定名称的nodelist
        NodeList bookNodes = root.getElementsByTagName_r("book")
;
        for (int i = 0; i < bookNodes.getLength(); i++)
        {
            Element bookeElement = (Element) bookNodes.item(i);
            Book book = new Book();
            book.setId(Integer.parseInt(bookeElement.getAttribute("id")));
            NodeList childNodes = bookeElement.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++)
            {
                if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE)
                {
                    if ("name".equals(childNodes.item(j).getNodeName()))
                    {
                        book.setName(childNodes.item(j).getFirstChild()
                                .getNodeValue());
                    }
                    else if ("price".equals(childNodes.item(j).getNodeName()))
                    {
                        book.setPrice(Float.parseFloat(childNodes.item(j)
                                .getFirstChild().getNodeValue()));
                    }
                }
            }
            list.add(book);
        }
        return list;

    }


2. Dom4j解析 XML:


   下载Dom4j的jar包:dom4j-1.6.1.jar 添加到项目中  会用到的一些方法:

一、DOM4j中,获得Document对象的方式有三种:

1.读取XML文件,获得document对象                                SAXReader reader = new SAXReader();                       Document   document = reader.read(new File("csdn.xml"));  //也可以用输入流2.解析XML形式的文本,得到document对象.                    String text = "<csdn></csdn>";                                Document document = DocumentHelper.parseText(text);  3.主动创建document对象.                   Document document = DocumentHelper.createDocument();             //创建根节点                   Element root = document.addElement("csdn");  

二、节点对象操作的方法:

1.获取文档的根节点.        Element root = document.getRootElement();      2.取得某个节点的子节点.        Element element=node.element(“四大名著");      3.取得节点的文字          String text=node.getText();      4.取得某节点下所有名为“csdn”的子节点,并进行遍历.         List nodes = rootElm.elements("csdn");            for (Iterator it = nodes.iterator(); it.hasNext();) {           Element elm = (Element) it.next();        // do something   }       5.对某节点下的所有子节点进行遍历.            for(Iterator it=root.elementIterator();it.hasNext();){                Element element = (Element) it.next();               // do something    }1.取得某节点下的某属性    Element root=document.getRootElement();        //属性名name           Attribute attribute=root.attribute("id");      2.取得属性的文字      String text=attribute.getText();      3.删除某属性 Attribute attribute=root.attribute("size"); root.remove(attribute);      4.遍历某节点的所有属性           Element root=document.getRootElement();               for(Iterator it=root.attributeIterator();it.hasNext();){                     Attribute attribute = (Attribute) it.next();                      String text=attribute.getText();                     System.out.println(text);      }  

完整例子:

   要解析的XMl文档: 

<?xml version="1.0" encoding="UTF-8"?> <doc> <person id="1" sex="m">       <name>zhangsan</name>           <age>32</age>         <adds>             <add code="home">home add</add>             <add code="com">com add</add>         </adds>     </person>     <person id="2" sex="w">          <name>lisi</name>             <age>22</age>         <adds>              <add code="home">home add</add>              <add code="com">com add</add>         </adds>     </person> </doc>

  解析代码: 

public class MainActivity extends Activity {private Person person;private List<Person> list;private InputStream is;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);list = new ArrayList<Person>();try {is = getAssets().open("test.xml");} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}SAXReader reader = new SAXReader();try {Document document = reader.read(is);Element root = document.getRootElement();for(Iterator iter=root.elementIterator();iter.hasNext();){person = new Person();Element element = (Element)iter.next();Attribute attr_id = element.attribute("id");Attribute attr_sex = element.attribute("sex");String id = attr_id.getValue();person.setID(id);String sex = attr_sex.getValue();person.setSex(sex);for(Iterator itera=element.elementIterator();itera.hasNext();){Element elementt = (Element)itera.next();if(elementt.getName().equals("name")){String name = elementt.getText();person.setName(name);}else if(elementt.getName().equals("age")){String age = elementt.getText();person.setAge(age);}else if(elementt.getName().equals("adds")){for(Iterator itere=elementt.elementIterator();itere.hasNext();){Element ele = (Element)itere.next();Attribute temp = ele.attribute("code");String tem = temp.getValue();if("home".equals(tem)){String home = ele.getText();person.setHome(home);}else if("com".equals(tem)){String com = ele.getText();person.setCom(com);}}}}list.add(person);person = null;}for(Person person:list){System.out.println(person.toString());}} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}}




原创粉丝点击