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.
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.
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.
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.
Your node is an Element so you just have to
Element e = (Element)node; String name = e.getAttribute("name");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With