Android下解析xml檔案的三種方式分别是:SAX、DOM、PULL,本次主要講解如何使用DOM方式:
這裡使用的測試xml檔案内容如下:
<?xml version="1.0" encoding="utf-8"?>
<ProjectSettings>
<CurrentProject>0</CurrentProject>
<Project>
<Name>FreeDemo</Name>
<RunningMode>1</RunningMode>
</Project>
</ProjectSettings>
解析代碼如下:
package com.freesoft.utility.logger;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 com.freesoft.utility.IntWrapper;
import com.freesoft.utility.settings.ProjectSetting;
/**
* @author wangshaozhuang
*
*/
public class DOMConfigGetter {
/**
* @param is
* 輸入流
* @return 項目設定
*/
public static ProjectSetting getConfig(InputStream is) {
ProjectSetting currentSetting = new ProjectSetting();
int currentProjectIndex = 0;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
Element root = document.getDocumentElement();
NodeList currentProjectNodeList = root.getElementsByTagName(ProjectSetting.CURRENTPROJECT_NAME);
if (currentProjectNodeList.getLength() != 1)
throw new ArrayIndexOutOfBoundsException();
else
currentProjectIndex = IntWrapper.wrap(currentProjectNodeList.item(0).getFirstChild().getNodeValue(), 0);
NodeList projectsNodeList = root.getElementsByTagName(ProjectSetting.PROJECT_NAME);
Node currentProjectNode = projectsNodeList.item(currentProjectIndex);
NodeList currentProjectSettingsNodeList = currentProjectNode.getChildNodes();
for (int i = 0; i < currentProjectSettingsNodeList.getLength(); i++ ) {
if (currentProjectSettingsNodeList.item(i).getNodeName().equals(ProjectSetting.RUNNINGMODE_NAME)) {
String value = currentProjectSettingsNodeList.item(i).getFirstChild().getNodeValue();
currentSetting.setRunningMode(IntWrapper.wrap(value, ProjectSetting.INVALID_MODE));
} else if (currentProjectSettingsNodeList.item(i).getNodeName().equals(ProjectSetting.NAME_NAME)) {
String value = currentProjectSettingsNodeList.item(i).getFirstChild().getNodeValue();
currentSetting.setName(value);
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return currentSetting;
}
}
分析整個解析過程,主要有如下思路:
- 通過DocumentBuilderFactory.newInstance()建立工廠;
- 通過工廠建立DocumentBuilder;
- 通過builder.parse得到一個Document對象,此時将檔案加載到了記憶體中;
- 通過document.getDocumentElement()得到整個文檔的root節點;
- 通過root.getElementsByTagName可以得到整個root的子節點;
- 子節點再查找孫子節點可以使用getChildNodes方法;
- 可以通過getNodeName().equals對比屬性名稱;
- 可以通過NodeList.item(i).getFirstChild().getNodeValue()得到屬性值;