Android使用XStream解析xml檔案
最近有個需求要在裝置配置指定靜態ip,因為裝置很多,所以打算採用配置檔案的形式,json和xml都可以,這裡採用xml
1、Android+Studio/">Android Studio整合XStream
這裡是採用整合jar包的形式,可以在官網下載jar包ofollow,noindex">官網下載 ,筆者下載的版本是1.4.1,整合jar包很簡單,把工程切換到project形式,把jar包拷到libs目錄下右鍵點選add library即可
成功匯入後在app/gradle下可以看到:
implementation files('libs/xstream-1.4.1.jar')
2、解析指定目錄的xml檔案
這裡採用的目錄在sdcard/放入檔案deviceip.xml內容如下:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?> <devices> <mask>255.255.255.0</mask> <gatway>192.168.1.1</gatway> <dns1>8.8.8.8</dns1> <dns2>8.8.4.4</dns2> <item> <mac>6C:5C:3D:00:58:5F</mac> <ip>192.168.1.128</ip> </item> <item> <mac>66:22:33:44:55:66</mac> <ip>192.168.1.121</ip> </item> </devices>
注意:這個xml檔案有list的內容
bean類:IpConfig
@XStreamAlias("devices") public class IpConfig { @XStreamAsAttribute() private String mask; private String gatway; private String dns1; private String dns2; @XStreamImplicit() private List<IpItem> ipItems = new ArrayList<IpItem>(); }
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(); } }