有下列文件,我要读取context-param里的所有元素的值,并以hashmap返回,能实现吗?<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
jb-web-1</display-name>
<context-param>    
    <param-name>myname</param-name>
        <param-value>abcdefghijk</param-value>
    </context-param>
    <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
   </welcome-file-list>
</web-app>

解决方案 »

  1.   

    只尝试过读取web.xml中servlet中的<init-param>不知有没有帮助。
    String ip = (String) getServlet().getServletConfig().getInitParameter("ip");实现应该是可以实现的,做一个循环,读取一个节点就放一个进map里面去
      

  2.   

    不是,我想要的是java怎样读xml文件。
      

  3.   

    HashMap hp = new HashMap();
    try{
    XmlDocument x = XmlDocument.createXmlDocument(yourxml);
    NodeList nl = x.getDocumentElement().getElementsByTagName("context-param").item(0).getChildNodes(); for(int i=0;i<nl.getLength();i++)
    if(nl.item(i).hasChildNodes()){
    hp.put(nl.item(i).getNodeName(),nl.item(i).getChildNodes().item(0).getNodeValue() );
    }
    }catch(Exception e){} System.out.println(hp);
      

  4.   

    我用的xml测试文件就是你给的以上题目中的内容,如果xml改成其他形式的话,自己再修改吧.
      

  5.   

    Element ownerElement = null;
    Document document = read(xmlfileName);
    String regex = "//context-param[normalize-space(param-name)='myname'";
    List list = document.selectNodes(regex);
    Iterator iter = list.iterator();
    if (iter.hasNext()) {
    ownerElement = (Element) iter.next();//取出集合中第一个
    }
    //说明上面代码中对象ownerElement代表context-param接点元素对象
    //下面这个元素所包含的一些参数值
    String  param_name=ownerElement.elementTextTrim("param-name");
    String  param_value=ownerElement.elementTextTrim("param-value");
    //下面就是将取出的值放到hashmap中应该比较简单我就不写出来.
    //注:上面方法中最后两行代码只适应于单一元素值不适合下面情况
    <context-param>    
     <param-name>myname</param-name>
              <param-value>abcdefghijk</param-value>
              <param-name>code</param-name>
              <param-value>big5</param-value>
        </context-param>
       <context-param>    
    <param-name>youname</param-name>
             <param-value>579tfouyg</param-value>
       </context-param>
    需要用Element.elements(String name)方法或Element.elementIterator(String name) 方法取得集合然后再使用循环的方式取值。 
      

  6.   

    楼上的大哥阿,你们用的是dom4j吗?
    import一下色。
      

  7.   

    楼上的大哥阿,你们用的是dom4j吗?
    import一下色。
      

  8.   


    import org.apache.crimson.tree.XmlDocument;
    import org.w3c.dom.NodeList;
      

  9.   

    @shan111
    import org.apache.crimson.tree.XmlDocument  //报错是不是还要下载其他的包?
      

  10.   

    下载 url
    http://xml.apache.org/dist/crimson/