document读取xml文件

此文讲述的是通过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,大家可以参考下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值