Android使用XStream解析xml文件

最近有个需求要在设备配置指定静态ip,因为设备很多,所以打算采用配置文件的形式,json和xml都可以,这里采用xml

1、Android Studio集成XStream

这里采用集成jar包的形式,可以在官网下载jar包 官网下载,笔者下载的版本是1.4.1,集成jar包很简单,把工程切换到project形式,把jar包拷到libs目录下右键点击add library即可

成功导入后在app/gradle下可以看到:


implementation files('libs/xstream-1.4.1.jar')

2、解析指定目录的xml文件

这里采用的目录在sdcard/放入文件deviceip.xml,内容如下:



    
        255.255.255.0
        192.168.1.1
        8.8.8.8
        8.8.4.4
        
            6C:5C:3D:00:58:5F
            192.168.1.128
        
        
            66:22:33:44:55:66
            192.168.1.121
        
    

注意:这个xml文件有list的内容,注意bean类的书写。
读取sdcard需要要加入权限:

    
    

bean类:IpConfig

@XStreamAlias("devices")
public class IpConfig {
    @XStreamAsAttribute()          
    private String mask;
    private String gatway;
    private String dns1;
    private String dns2;

    @XStreamImplicit()
    private List ipItems = new ArrayList();
}

IpItem :

@XStreamAlias("item")
public class IpItem {
    @XStreamAsAttribute()
    private String mac;
    private String ip;
}

注意这三个注解:

@XStreamAlias
@XStreamImplicit
@XStreamAsAttribute

解析方法:

    private final String deviceXmlName = "deviceip.xml";
    private void parseIpConfig() {
        Log.i(TAG, "开始解析网络配置文件...");
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
                Log.e(TAG, "系统异常");
                return;
        }

        File file = new File(Environment.getExternalStorageDirectory(), deviceXmlName);
        InputStream in = null;

        if (!file.exists()) {
            Log.e(TAG, "deviceip.xml不存在");
            return;
        }

        try {
            in = new FileInputStream(file);
            XStream xStream = new XStream();
            xStream.processAnnotations(IpConfig.class);
            IpConfig ipConfig = (IpConfig) xStream.fromXML(in);
            mIpConfig = ipConfig;
            Log.d(TAG, "ipConfig = " + ipConfig.toString());
        } catch (IOException e) {
            Log.e(TAG, " xml解析异常 :" + e.toString());
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

当然deviceip.xml文件也可以放到app的assets目录下面去

try {
    InputStream in;
    in = getResources().getAssets().open("deviceip.xml");
    XStream xStream = new XStream();
    xStream.processAnnotations(IpConfig.class);
    IpConfig ipConfig = (IpConfig) xStream.fromXML(in);
} catch (IOException e) {
    e.printStackTrace();
} finally {
     try {
         in.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
 }

你可能感兴趣的:(Android使用XStream解析xml文件)