XML文件配置转化对象使用

来源:互联网 发布:如何评价宋思明知乎 编辑:程序博客网 时间:2024/06/05 20:49

        我们在做移动开发的时候,会把一些变化的,或者固定的配置信息放到一个地方进行同意管理,存储。

        起初的开发者,一般会直接放到一个类中,以静态的方式存放。比如请求地址url,数据库配置信息的数据库名,表名,字段名等。到了后来,需要配置的信息慢慢变的越来越多,那么就统一到一个专门的配置文件中放到资源里面,设定好数据存放规则,以一定的方式来读取配置信。

        再到后来,又有升级的概念,如果需要动态的从服务器改变这些参数,只需要和服务器进行迭代升级,更新这个文件就可以进行动态的从服务器修改客户端的配置信息,那么这需要对文件进行版本的处理。这已经是很好的管理这些配置信息的方式了。

         说到这里,那么为什么我还要提出这个XML文件配置转化对象使用呢?因为在配置文件中,都是通过读取文件获取String,或者int,long,double,float,这些的数据在代码中使用,比如数据库名,表名,字段名字,等。这些都是一个一个的分散的的字符串,那么如果把一个数据库的这些固定配置当作一个对象呢,就非常容易调用了,只需要调用这个对象,那么关于数据库的所有的配置都在这个对象里面,如果想修改这个数据库,也会很方便的找到这个数据库配置对象。也会使新的参与开发者容易理解,看的懂这些数据。不再按照字符串一个一个找那些配置信息了。只需要找到数据的配置对象,就知道了所有的数据配置。大大提交可读性,还有可修改。和服务器进行对比升级文件也会很容易的多。

说了那么多的优点,接下来上例子:

       

        把配置文件放到sestes目录下,如果是对象则:

             如果是列表则:

        如果是字符串则:

        如果对象中引用某个 字符串则,对象中的属性是对象,且不是引入::

        如果是对象,引入对象,则是:

 


          代码:

package com.xiaoyunchengzhu.xmlconvertobject.Configuration;import android.content.Context;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.lang.reflect.Field;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;/** * Created by zhangshiyu on 2016/4/13. */public class ConfigResourcesSection {    private InputStream inputStream;    public ConfigResourcesSection(boolean isAssets)    {        if (isAssets)        {            inputStream=getUrlStringStream();        }else {            //undo 应该自定义在本地中的文件流        }    }    /**     * assets's resource     * @return     */    private  InputStream getUrlStringStream()    {        String path="/assets/Configuration/configResource.xml";        InputStream inStream = ConfigResourcesSection.class.getResourceAsStream(path);        return inStream;    }    /**     * you can user-defined resouce'path.in sdcard.     * @param context     * @return     */    private  InputStream getUrlStringStream(Context context)    {        String path=context.getFilesDir().getAbsolutePath()+"/configResource.xml";        File file=new File(path);        InputStream inputStream=null;        try {             inputStream=new FileInputStream(file);        } catch (FileNotFoundException e) {            e.printStackTrace();        }        return inputStream;    }    /**     *     * listItem     * @param urlNode     * @return     */    public      Object getValueFromUrlNode(Node urlNode,ConfigConverter configConverter)    {        Object o=null;        try {            Node type1 = urlNode.getAttributes().getNamedItem("Type");            if (type1== null ) {                String className = urlNode.getAttributes().getNamedItem("Class").getNodeValue();                Class<?> aClass = Class.forName(className);                o = aClass.newInstance();                for (int i = 0; i < urlNode.getAttributes().getLength(); i++) {                    String nodeName = urlNode.getAttributes().item(i).getNodeName();                    if (!nodeName.equals("Id") && !nodeName.equals("Class")&&!nodeName.equals("propertyName")) {                        Field declaredField = aClass.getDeclaredField(nodeName);                        declaredField.setAccessible(true);                        String value = urlNode.getAttributes().item(i).getNodeValue();                        if (!value.startsWith("@")) {                            String type = declaredField.getType().toString();                            if (type.endsWith("int")) {                                declaredField.setInt(o, Integer.valueOf(value));                            } else if (type.endsWith("double")) {                                declaredField.setDouble(o, Double.valueOf(value));                            } else if (type.endsWith("char")) {                                declaredField.setChar(o, value.charAt(0));                            } else if (type.endsWith("byte")) {                                declaredField.setByte(o, Byte.valueOf(value));                            } else if (type.endsWith("boolean")) {                                declaredField.setBoolean(o, Boolean.valueOf(value));                            } else if (type.endsWith("float")) {                                declaredField.setFloat(o, Float.valueOf(value));                            } else if (type.endsWith("long")) {                                declaredField.setLong(o, Long.valueOf(value));                            } else if (type.endsWith("short")) {                                declaredField.setShort(o, Short.valueOf(value));                            } else {                                declaredField.set(o, value);                            }                        }else {                            declaredField.set(o,configConverter.convert(getId(value),getType(value)));                        }                    }                }                NodeList childNodes = urlNode.getChildNodes();                for (int i=0;i<childNodes.getLength();i++)                {                    if (childNodes.item(i).getNodeName().equals("add"))                    {                        Node propertyName = childNodes.item(i).getAttributes().getNamedItem("propertyName");                        Node type = childNodes.item(i).getAttributes().getNamedItem("Type");                        Field declaredField = aClass.getDeclaredField(propertyName.getNodeValue());                        declaredField.setAccessible(true);                        if (type!=null) {                            declaredField.set(o, configConverter.convert(childNodes.item(i).getAttributes().getNamedItem("Id").getNodeValue(), type.getNodeValue()));                        }else {                            declaredField.set(o,getValueFromUrlNode(childNodes.item(i), configConverter));                        }                    }                }                }else {                o= configConverter.convert(urlNode.getAttributes().getNamedItem("Id").getNodeValue(),urlNode.getAttributes().getNamedItem("Type").getNodeValue());            }        }catch(ClassNotFoundException e){                e.printStackTrace();            }catch(InstantiationException e){                e.printStackTrace();            }catch(IllegalAccessException e){                e.printStackTrace();            }catch(NoSuchFieldException e){                e.printStackTrace();            }        return  o;    }    /**     * root element     * @return     */    public  Element getRootElement()    {        Document document=null;        //DOM文件创建工厂        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        //DOM创建对象        DocumentBuilder builder = null;        try {            builder = factory.newDocumentBuilder();        //获取XML的DOM         document = builder.parse(inputStream);        } catch (ParserConfigurationException e) {            e.printStackTrace();        } catch (SAXException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return document.getDocumentElement();    }    /**     *     * @param value example @String/id     * @return   Type     */    private String getType(String value)    {        return value.substring(1,value.indexOf("/"));    }    /**     *     * @param value example @String/id     * @return Id     */    private String getId(String value)    {        return value.substring(value.indexOf("/")+1,value.length());    }}

上代码,这是配置xml读取方式的处理类。

 

package com.xiaoyunchengzhu.xmlconvertobject.Configuration;/** * Created by zhangshiyu on 2016/4/13. * converter abstract class. */public abstract class ConfigConverter<T> {    ConfigResourcesSection urlResourcesSection=new ConfigResourcesSection(true);    abstract T convert(String id);    public Object  convert(String id,String type){        ConfigManger configManger=new ConfigManger();        return configManger.convert(id,type);    }}
这是转化对象类型的抽象类。

package com.xiaoyunchengzhu.xmlconvertobject.Configuration;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;/** * Created by zhangshiyu on 2016/4/13. */public class ObjectConverter extends ConfigConverter  {    private String node;    public ObjectConverter(String node)    {        this.node=node;    }    @Override    public Object convert(String id) {        Object o=null;        Element rootElement = urlResourcesSection.getRootElement();        Element element = (Element)rootElement.getElementsByTagName(node).item(0);        NodeList add = element.getElementsByTagName("add");        for (int i=0;i<add.getLength();i++)        {            Node id1 = add.item(i).getAttributes().getNamedItem("Id");            if (id1!=null) {                if (id1.getNodeValue().equals(id) && add.item(i).getAttributes().getNamedItem("Type") == null) {                    o = urlResourcesSection.getValueFromUrlNode(add.item(i), this);                }            }        }        return o;    }}
这是对象转化类。

package com.xiaoyunchengzhu.xmlconvertobject.Configuration;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import java.util.ArrayList;import java.util.List;/** * Created by zhangshiyu on 2016/4/13. */public class ListConverter extends ConfigConverter  {    private String node;    public ListConverter(String node)    {        this.node=node;    }    @Override    public Object convert( String id) {        List<Object> l=null;        Element rootElement = urlResourcesSection.getRootElement();        Element itemList = (Element)rootElement.getElementsByTagName(node).item(0);        NodeList li = itemList.getElementsByTagName("li");        for (int i=0;i<li.getLength();i++)        {            Node id1 = li.item(i).getAttributes().getNamedItem("Id");            if (id1!=null) {                if (id1.getNodeValue().equals(id) && li.item(i).getAttributes().getNamedItem("Type") == null) {                    Element item1 = (Element) li.item(i);                    NodeList add = item1.getElementsByTagName("add");                    NodeList string = item1.getElementsByTagName("string");                    l = new ArrayList<>();                    if (add.getLength() > 0) {                        for (int j = 0; j < add.getLength(); j++) {                            l.add(urlResourcesSection.getValueFromUrlNode(add.item(j), this));                        }                    } else if (string.getLength() > 0) {                        for (int j = 0; j < string.getLength(); j++) {                            l.add(string.item(j).getTextContent());                        }                    }                }            }        }        return l;    }}
这是列表转化类,这里用的是list列表;

package com.xiaoyunchengzhu.xmlconvertobject.Configuration;import org.w3c.dom.Element;import org.w3c.dom.NodeList;/** * Created by zhangshiyu on 2016/4/14. */public class StringConverter extends ConfigConverter{    private String node;    public StringConverter(String node)    {        this.node=node;    }    @Override    Object convert(String id) {        Object o=null;        Element rootElement = urlResourcesSection.getRootElement();        Element element = (Element)rootElement.getElementsByTagName(node).item(0);        NodeList add = element.getElementsByTagName("string");        for (int i=0;i<add.getLength();i++)        {            if (add.item(i).getAttributes().getNamedItem("Id").getNodeValue().equals(id))            {                   Element element1= (Element) add.item(i);                o=element1.getTextContent();            }        }        return o;    }}
这是字符串转化类;

package com.xiaoyunchengzhu.xmlconvertobject.Configuration;/** * Created by zhangshiyu on 2016/4/13. * manage converter'object,xml to object. */public class ConfigManger {    private ConfigConverter configConverter;    public  String listNode="List";    public  String objectNode="Object";    public  String stringNode="String";    public Object convertList(String id)    {        configConverter=new ListConverter(listNode);        return  configConverter.convert(id);    }    public Object convertObject(String id)    {        configConverter=new ObjectConverter(objectNode);        return configConverter.convert(id);    }    public Object convertString(String id)    {        configConverter=new StringConverter(stringNode);        return configConverter.convert(id);    }    protected Object convert(String id,String type)    {        Object o=null;          if (type.equals(listNode))          {              o= convertList(id);          }else if (type.equals(objectNode))          {              o= convertObject(id);          }else if (type.equals(stringNode))          {              o=convertString(id);          }        return o;    }}
这是统一转化管理类;

这些对象的bean类就不列举了。

package com.xiaoyunchengzhu.xmlconvertobject;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.View;import android.view.Menu;import android.view.MenuItem;import android.widget.Button;import android.widget.TextView;import com.google.gson.Gson;import com.xiaoyunchengzhu.xmlconvertobject.Configuration.ConfigManger;import com.xiaoyunchengzhu.xmlconvertobject.model.DataUrlBean;import com.xiaoyunchengzhu.xmlconvertobject.model.Person;import com.xiaoyunchengzhu.xmlconvertobject.model.Response;import java.util.List;import butterknife.ButterKnife;import butterknife.InjectView;public class MainActivity extends AppCompatActivity implements View.OnClickListener{    @InjectView(R.id.show)     TextView show;    @InjectView(R.id.showlist1)     Button showList1;    @InjectView(R.id.showlist2)    Button showList2;    @InjectView(R.id.showlist3)    Button showList3;    @InjectView(R.id.dataUrlBean1)    Button showdataUrlBean1;    @InjectView(R.id.person1)    Button showperson1;    @InjectView(R.id.response1)    Button showresponse1;    @InjectView(R.id.response2)    Button showresponse2;    @InjectView(R.id.showlihua)    Button showshowlihua;    @InjectView(R.id.showboy1)    Button showshowboy1;    @InjectView(R.id.showerror)    Button showshowerror;    Gson gson;    ConfigManger configManger;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ButterKnife.inject(this);        gson=new Gson();        configManger=new ConfigManger();        inite();    }    private void inite()    {        showList1.setOnClickListener(this);        showList2.setOnClickListener(this);        showList3.setOnClickListener(this);        showdataUrlBean1.setOnClickListener(this);        showperson1.setOnClickListener(this);        showresponse1.setOnClickListener(this);        showresponse2.setOnClickListener(this);        showshowlihua.setOnClickListener(this);        showshowboy1.setOnClickListener(this);        showshowerror.setOnClickListener(this);    }    @Override    public void onClick(View v) {        String content=null;        switch (v.getId())        {            case R.id.showlist1:                List<DataUrlBean> list1= (List<DataUrlBean>) configManger.convertList("list1");                content=gson.toJson(list1);                break;            case R.id.showlist2:                List<String> list2= (List<String>) configManger.convertList("list2");                content=gson.toJson(list2);                break;            case R.id.showlist3:                List<Response> list3= (List<Response>) configManger.convertList("list3");                content=gson.toJson(list3);                break;            case R.id.dataUrlBean1:                DataUrlBean dataUrlBean1= (DataUrlBean) configManger.convertObject("dataUrlBean1");                content=gson.toJson(dataUrlBean1);                break;            case R.id.person1:                Person person1= (Person) configManger.convertObject("person1");                content=gson.toJson(person1);                break;            case R.id.response1:                Response response1= (Response) configManger.convertObject("response1");                content=gson.toJson(response1);                break;            case R.id.response2:                Response response2= (Response) configManger.convertObject("response2");                content=gson.toJson(response2);                break;            case R.id.showlihua:                content= (String) configManger.convertString("lihua");                break;            case R.id.showboy1:                content= (String) configManger.convertString("boy1");                break;            case R.id.showerror:                content= (String) configManger.convertString("error");                break;        }        show.setText(content);    }}
        这是展示类。在activity里面展示转化对象的结果,由json的方式展示。

        代码放到这里,也该明白了,这不是一个专门的安卓的工具。这是一个Java的工具。

        源码地址:https://github.com/xiaoyunchengzhu/XmlConvertObject


1 0
原创粉丝点击