Henk Jansen
Henk Jansen

Reputation: 1142

Returning an element with a specific attribute JDOM

i need your help on a particular bit of code.

I have a document object in jdom. I also do have a element object for the root. Now i want to get a specific element based on the value of an attribute. But what i want to avoid, is to filter through the complete list of children, just to get one element. So is there some kind of way to filter on the value of a document.

Lets say my attribute value is '123'

Now i want the element where the 'id' value is '123'

What is the best way to do this?

Kind Regards.

Upvotes: 0

Views: 1994

Answers (2)

Howard Schutzman
Howard Schutzman

Reputation: 2135

If I were confronted with this problem, I would solve it one of two ways:

1) If I only needed to search the elements once to find the element with the particular attribute value, I would do a simple searh. The advantage (and disadvantage) of JDOM is it puts the entire document in memory, so searching through elements is very quick, even if there are many elements. Even if you use XPath (and I admit to being unfamiliar with it, but found the previous answer enlightening), odds are they would be doing the same thing, so this solution is probably no less efficient. In general, using pre-built solutions can save you from having to write code (although in this case your own code would be pretty small), but are usually no more efficient and often less efficient, since you are using a generalized solution that is not specifically tailored to your needs.

2) If I needed to do multiple searches, then I would build a HashMap where the key was the attribute value.

If you think either of these solutions has merit but have some additional questions or would like some sample code, please feel free to email me for further information.

Upvotes: 2

Guillaume Polet
Guillaume Polet

Reputation: 47617

I would use XPath for that. With the following expression: //element[@attribute='value']

Upvotes: 3

Related Questions