当前位置: 代码迷 >> Java Web开发 >> (答案)如何取XML节点的属性
  详细解决方案

(答案)如何取XML节点的属性

热度:48   发布时间:2016-04-17 01:20:44.0
(在线等答案)怎么取XML节点的属性?
<?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();
}
}
}
  相关解决方案