need to extract for iteration through all values contained in <genre>XXXXX</genre> elements in an XML file.

I need to extract for validation against a controlled list of acceptable values all of the items contained in a <genre>xxxx</genre> xml file.  I could do this by writing my own string parser, but I'm guessing there is a cleaner, "best practice" kind of way to do this using JDOM, SAX or another xml parser.  Help appreciated.
Who is Participating?
enachemcConnect With a Mentor Commented:
you could use XPath for this. The string for this would be "//genre".

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
PathExpression expr = xpath.compile("//genre");
Object result = expr.evaluate(doc, XPathConstants.NODESET);

 NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
wizcarlAuthor Commented:
Sorry for the uneducated followup, but I just downloaded the org.apache.xalan jar file and it doesn't contain the XPath nor XPathFactory classess.  Do you know where I can get these jar files?
javax.xml.xpath.XPathExpression (for PathExpression, sorry for the typo)

All of the above are included in the Java 1.5 SDK
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

wizcarlAuthor Commented:
Thank you.  I made these changes, and now the code is throuwing an java interal error at the line:

Object result = expr.evaluate(doc, XPathConstants.NODESET)

I think I'm feeding it the wrong kind of input object.  In my code, "doc" is  a string variable that contains all of the xml.  Any ideas of what it needs to be?
for a more simpler and complete example, check out
You should supply a parsed document or xml element, not a string.
wizcarlAuthor Commented:
Just as a follow up, I tried changing the "doc" variable from a String to an Object and it thre the same error:

Exception in thread "main" java.lang.ClassCastException: java.lang.String
      at org.nines.NinesCollexImporter.validateValues(
      at org.nines.NinesCollexImporter.main(
girionisConnect With a Mentor Commented:
The "doc" should be of Document type and not String, otherwise you cannot perform xpath queries on it. YO should turn the string into an XML document first before you proceed.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.