您的位置:首页 > 其它

document读取xml文件

2012-08-10 10:54 281 查看
此文讲述的是通过doc方式解析

1、 得到xml文件

public static Document getDocument(String name) {

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

Document document = null;

DocumentBuilder db = null;

try {

db = dbf.newDocumentBuilder();

String url = XmlUtil.class.getResource("/").getPath();

if(url.contains("%20"))

url = url.replace("%20", " ");//此处是为了防止因为路径有空格,导致无法读取xml文件。

document = db.parse(url+"/"+name+".xml");

} catch (ParserConfigurationException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return document;

}

2 得到指定文件

Document d = XmlUtil.getDocument("heat");//得到项目根路径下的heat.xml文件

Element e = (Element) d.getElementsByTagName("arealevel").item(0);得到标签arealevel的元素

关于xml的一个面试题:

问: 简单说说xml的解析方式

答:两种方式,DOC方式和SAX方式,DOC是加载整个xml文档,再进行解析,而SAX是你需要解析哪部分就加载哪部分。一般情况下内容不多的xml通过DOC全部加载,对于xml内容多的使用SAX加载。

问:如何知道xml内容多与否

答:内容不是动态的,不会随着程序的运行增加内容。(这个答案是人家给的,觉得稍微比较有道理的,因为我自己当时是不清楚这个问题的答案的。)

关于DOC和SAX的区别,推荐篇文章:http://blog.sina.com.cn/s/blog_4cf3bd2501000cg1.html,大家可以参考下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: