[jdom-interest] return specific XML node within a for-loop

Phil Weighill Smith phil.weighill-smith at volantis.com
Tue Aug 16 12:46:07 PDT 2005


I personally would use an XPath expression (JDOM has an XPath mechanism
but you will need to include additional JARs on your classpath). To get
the description for a given coffeeName element you can do something
like:

public String getCoffeeDesc(Document doc, String coffeeName) {
    XPath xpath = XPath.newInstance("//row[./coffeeName/text() = " +
coffeeName + "]/coffeeDesc/text()");
    Text coffeeDesc = (Text)xpath.selectSingleNode(doc);
    return coffeeText.value();
}

Hope that helps.

Phil :n)

On Tue, 2005-08-16 at 15:40 +0100, Khorasani, Houman wrote:
> Hello,
> 
> I am new to JDOM and would like to know how I could solve this.
> I have an existing XML file like this:
> 
> <?xml version="1.0" encoding="UTF-8"?>
> <data>
> 	<row>
> 		<coffeeName>Esperesso</coffeeName>
> 		<coffeeDesc>Very Strong, very small</coffeeDesc>
> 	</row>
> 	<row>
> 		<coffeeName>Capuccino</coffeeName>
> 		<coffeeDesc>Not so strong, middle size</coffeeDesc>
> 	</row>
> 	<row>
> 		<coffeeName>Caffee Late</coffeeName>
> 		<coffeeDesc>Weak, big size</coffeeDesc>
> 	</row>
> </data>
> 
> 
> I would like to have a method that contains a for-loop and return the
> description for the coffeeName.
> 
> public String getCoffeeDesc(String coffeeName) {
> ???
> }
> 
> SAXBuilder builder = new SAXBuilder();
> Document doc = builder.build(new File("C://dev//coffee.xml"));
>            
> Element root = doc.getRootElement();
> List children = root.getChildren();
> 
> System.out.println(getCoffeeDesc("Esperesso"));
> 
> I have all the children of root within "children" but how shall I
> proceed at this point the best way?   
> 
> Many Thanks
> Houman
> 
> 
> 
> 


More information about the jdom-interest mailing list