<?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的值?
------解决方案--------------------
假设你的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();
}
}
}