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。NodeList;
import org.xml.sax.SAXException;
void ReadXML()
{
DocumentBuilderFactory docBuilderFactory = null;
DocumentBuilder docBuilder = null;
Document doc = null;
try {
docBuilderFactory = DocumentBuilderFactory。newInstance();
docBuilder = docBuilderFactory。newDocumentBuilder();
//xml file 放到 assets目录中的
doc = docBuilder.parse(getResources().getAssets().open(”weather.xml”));
//root element
Element root = doc。getDocumentElement();
//Do something here
//get a NodeList by tagname
NodeList nodeList = root。getElementsByTagName(”tag”);
for(int i =0;i< nodeList。getLength();i++)
{
Node nd = nodeList.item(i);
//Read Node
}
} catch (IOException e) {
} catch (SAXException e) {
} catch (ParserConfigurationException e) {
} finally {
doc = null;
docBuilder = null;
docBuilderFactory = null;
}
}
此博客给出了在Android中使用DOM方式解析XML文件的代码示例。通过导入相关类,创建文档构建器工厂和构建器,解析assets目录下的weather.xml文件,获取根元素和指定标签的节点列表,并对节点进行读取操作。
1万+

被折叠的 条评论
为什么被折叠?



