2011-05-05 148 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()