Servlet和普通JAVA类中DOM解析问题

来源:互联网 发布:java 0转换0.00 编辑:程序博客网 时间:2024/06/15 19:13

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();­

   DocumentBuilder db=dbf.newDocumentBuilder();­

   String path=this.getInitParameter("datasource");­

   System.out.println("<<====="+path+"====>");­

   String realPath=this.getServletContext().getRealPath(path);­

   System.out.println("<<====="+realPath+"====>");­

   Document doc=db.parse(new File(realPath));­

   NodeList nl=doc.getElementsByTagName("data-sources");­

   Element el=(Element) nl.item(0);­

   NodeList dsnl=el.getElementsByTagName("*");­

   HashMap dshs=new HashMap();­

   for (int i = 0; i < dsnl.getLength(); i++) {­

    Element elChild=(Element) dsnl.item(i);­

    String key=elChild.getNodeName();­

    String value=elChild.getChildNodes().item(0).getNodeValue();­

    System.out.println("value==>>elChild.getChildNodes().item(0).getTextContent()"+elChild.getChildNodes().item(0).getNodeValue()+"=====>>>nodevalue "+value);­

    dshs.put(key, value);­

   }­

标记为红色的这条语句,如果你使用elChild.getChildNodes().item(0).getNodeValue()还没有问题,但是如果你改一下,使用的是elChild.getChildNodes().item(0).getTextContent(),那么就什么错也不报,然后就不向下走了。但是在类里,什么问题都没有。­

找了很久,找到了原因。想都想不到。­

从SERVLET里,通过初始化参数找到的真实路径问题。­

例如,我的路径是:C:/Documents and Settings/Administrator/桌面/tomcat/tomcat/webapps/MyStruts/WEB-INF/strutsconfig.xml;­

但是,我如果说是自己手动写进去的,哪么路径是:­

­

C://Documents and Settings//Administrator//桌面[url=file:////tomcat//tomcat//webapps//MyStruts//WEB-INF//strutsconfig.xml]//tomcat//tomcat//webapps//MyStruts//WEB-INF//strutsconfig.xml[/url]­

,这样,就报错了,­

但是如果是:­

C:/Documents and Settings/Administrator/桌面/tomcat/tomcat/webapps/MyStruts/WEB-INF/strutsconfig.xml;­

就没有问题。头疼啊,这也能出错,晕???但是普通类为什么没问题呢???­

郁闷中!