<?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的值?
<login>
<user age="22">
<name>邓小平</name>
<pwd>123</pwd>
</user>
<user age="44">
<name>毛择东</name>
<pwd>456</pwd>
</user>
</login>怎么可以取到age的值?
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());
}
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
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse("text.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();
}
}
}