Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml id attribute to work with Java's getElementById? [duplicate]

I have an xml document being parsed in Java as a w3c document. In my xml, i have many elements of the same name, e.g <item ..... />, each one with unique attribute's value, e.g <item name="a" .... />. I want in java to do:

doc.getElementById("a")

in order to get that specific item I have there with that name. How can I tell java to use 'name' as the id? Or, alternately, How can I fetch that specific item in least complexity?

like image 745
buddy123 Avatar asked Nov 19 '25 05:11

buddy123


2 Answers

DOM is not the best API to easily query your document and get back found elements. Learn XPath, which is a more appropriate API, or iterate through the tree of elements by yourself.

getElementById() will only return the element which has the given id attribute (edit: marked as such in the document DTD or schema). It can't find by name attribute.

See Java XML DOM: how are id Attributes special? for details.

like image 196
JB Nizet Avatar answered Nov 21 '25 18:11

JB Nizet


You need to write a DTD that defines your attribute as being of type ID.

like image 23
Martin Honnen Avatar answered Nov 21 '25 19:11

Martin Honnen