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;
就没有问题。头疼啊,这也能出错,晕???但是普通类为什么没问题呢???
郁闷中!
本文探讨了在Java中使用DOM解析XML文件时遇到的一个奇怪问题:使用`getTextContent()`与`getNodeValue()`方法获取节点值时的行为差异,并最终定位到路径问题导致的解析异常。

1135

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



