<?xml version="1.0" encoding="UTF-8"?>
<login>
<user age="22">
<name>邓小平</name>
<pwd>123</pwd>
</user>
<user age="44">
<name>毛择东</name>
<pwd>456</pwd>
</user>
</login>怎么可以取到age的值?

解决方案 »

  1.   


      NamedNodeMap   nnm   =   (   (Element)   node).getAttributes();   
      for   (int   j   =   0;j   <   nnm.getLength();j++)   
      {   
          Node   detailNode   =   nnm.item(j);   
          System.out.println(detailNode.getNodeName()+"   :"+detailNode.getNodeValue());   
      }
      

  2.   

    InputStream is=this.getClass().getResourceAsStream("你的XML.xml");
    try {
    Document doc=new SAXReader().read(is);
    Element rootE=doc.getRootElement();
    List<Element> list=rootE.elements();
    for (Element e : list) {
    String id=e.attributeValue("id");
    String className=e.attributeValue("class");
    hm.put(id, className);
    }
    } catch (DocumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    需要包dom4j.jar
      

  3.   

    我前面是这样做的,可不可以接着我的做。
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.parse("text.xml");
      

  4.   

    假设你的xml路径全名: conf/domfac.xml
    import java.io.IOException;import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;public class TestDomFactory {
    public static void main(String[] args) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    try {
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    Document d = db.parse("conf/domfac.xml");
    NodeList list = d.getElementsByTagName("user");
    for(int i=0;i<list.getLength();i++){
    System.out.println(list.item(i).getAttributes().item(0).getNodeValue());
    }
    } catch (SAXException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParserConfigurationException e) {
    e.printStackTrace();
    }
    }
    }