2011-05-05 151 views
33

我想獲得一個XML節點實例的屬性的屬性:獲取DOM節點

<Car name="Test"> 
</Car> 

我要搶車節點的名稱屬性。

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder();   
Document doc = db.parse(configFile); 
doc.getDocumentElement().normalize();   
NodeList layerConfigList = doc.getElementsByTagName("CAR"); 
Node node = layerConfigList.item(0); 
// get the name attribute out of the node. 

這是我卡住,因爲這看起來像我可以使用的唯一方法是的getAttributes()與回報的NamedNodeMap和林不知道如何從解壓縮。

回答

64

你的節點是一個元素,所以你只需要

Element e = (Element)node; 
String name = e.getAttribute("name"); 
+1

謝謝!它工作完美。 – MBU 2011-05-05 09:28:59

+0

我們如何才能通過名稱獲得價值。如果我只想要car1?例如 Taran 2016-04-01 21:26:22

13

你可以做到這一點,而不使用的元素,像這樣:

//HtmlTag represents any arbitrary node that you are trying to get its "car" attribute 

if("HtmlTag".equals(node.getNodeName())) 
String nodeContent=node.getAttributes().getNamedItem("car").getNodeValue()