Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an attribute of a dom node

Tags:

java

xml

jaxp

I am trying to get an attribute of an xml node example:

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

I want to grab the name attribute of the car node.

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. 

this is where i get stuck because the only method that looks like i can use is getAttributes() with returns a NamedNodeMap and im not sure how to extract it from that.

like image 656
MBU Avatar asked May 05 '11 09:05

MBU


People also ask

How do I get attributes in DOM?

HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.

What is attribute node in DOM?

The attributes property in HTML DOM returns the group of node attributes specified by NamedNodeMap objects. The NamedNodeMap object represents the collection of attribute objects and can be accessed by index number. The index number starts at 0.

How do I fetch DOM elements?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.


1 Answers

Your node is an Element so you just have to

Element e = (Element)node; String name = e.getAttribute("name"); 
like image 118
rurouni Avatar answered Oct 04 '22 05:10

rurouni