How to solve the XML parsing performance issue on Android

后端 未结 8 1871
耶瑟儿~
耶瑟儿~ 2020-12-25 08:31

I have to read a XML file with about ~4000 lines on Android. First I tried the SimpleXML library because it\'s the easiest and it took about 2 minutes on my HTC Desire. So I

8条回答
  •  感情败类
    2020-12-25 08:38

    I think the best way to work with XML on Android is use VDT-XML library

    My XML file contains more then 60 000 lines and VDT-XML handles it as following:

    Nexus 5 : 2055 millisec

    Galaxy Note 4 : 2498 milisec

    You can find more benchmark reports by link : VTD-XML Benchmark

    Short example of XML file

     
            20Fruit
    31Vegetables
    45Rice
    50Potatoes

    Configuration of "build.gradle" file

    dependencies {
        compile files('libs/vtd-xml.jar')
    }
    

    Source code example:

    import com.ximpleware.AutoPilot;
    import com.ximpleware.VTDGen;
    import com.ximpleware.VTDNav;
    
    
    String fileName = "products.xml";
    
    VTDGen vg = new VTDGen();
    
    if (vg.parseFile(fileName, true)) {
    
         VTDNav vn = vg.getNav();
         AutoPilot table = new AutoPilot(vn);
         table.selectXPath("database/table");
    
         while (table.iterate()) {
            String tableName = vn.toString(vn.getAttrVal("name"));
    
            if (tableName.equals("category")) {
                AutoPilot column = new AutoPilot(vn);
                column.selectElement("column");
    
                while (column.iterate()) {
                     String text = vn.toNormalizedString(vn.getText());
                     String name = vn.toString(vn.getAttrVal("name"));
    
                     if (name.equals("catId")) {
                        Log.d("Category ID = " + text);
                     } else if (name.equals("catName")) {
                        Log.d("Category Name = " + text);
                     } 
    
                }
            }
         }
    }
    

    Result

    Category ID = 20
    Category Name = Fruit
    
    Category ID = 31
    Category Name = Vegetables
    
    Category ID = 45
    Category Name = Rice
    
    Category ID = 50
    Category Name = Potatoes
    

    it works for me and hope it helps you.

提交回复
热议问题