[jdom-interest] getChild with Attribute
Kenworthy, Edward
edward.kenworthy at exchange.co.uk
Tue Apr 3 02:13:58 PDT 2001
Actually that wouldn't work. It wouldn't find any nested elements with the
attribute. You would need to use recursion to do that.
Here's a method I use (it uses the "name" attribute AND element type
(getName()) to work out whether it's a matching element.)
private Collection internalGetAllInstances(Element searchRoot, Element
element, Collection listOfMatches)
{
listOfMatches.add(element);
// check if there are multiple instances of the element
Attribute elementNameAtt = element.getAttribute(NAME_ATT);
if (elementNameAtt != null)
{
String elementName = elementNameAtt.getValue();
if (elementName.length() != 0)
{
List children = searchRoot.getChildren();
if (children.size() > 0)
{
Iterator iter = children.iterator();
while(iter.hasNext())
{
Element current = (Element)iter.next();
if (current.getName().equalsIgnoreCase(element.getName()))
{
Attribute nameAtt = current.getAttribute(NAME_ATT);
if (nameAtt != null)
{
String name = nameAtt.getValue();
if (name.length() != 0)
{
if (name.equalsIgnoreCase(elementName))
{
logger.debug("Everything matches, add it to the list.");
listOfMatches.add(current);
}
else
{
logger.debug("Types match, but name doesn't, so check
its children.");
internalGetAllInstances(current, element,
listOfMatches);
}
}
}
}
else
{
logger.debug("Types don't match, can't be the same, so check
its children.");
internalGetAllInstances(current, element, listOfMatches);
}
} // while
}
}
else
{
logger.debug("No name attribute set, can't have other instances");
}
}
else
{
logger.debug("No name attribute at all, can't have other instances");
}
return listOfMatches;
}
-----Original Message-----
From: Dave Writz [mailto:dave.writz at cornerstone.net]
Sent: 03 April 2001 04:23
To: jdom-interest at jdom.org
Subject: [jdom-interest] getChild with Attribute
Is it possible to get a child of an element based on a attribute value
without using XPath? I have been able to get it working with XPath, but am
hoping for a cleaner implementation.
What I am looking for is something like the following:
String value = document.getRootElement().root.getChild("ElementName", new
Attribute("name", "value")).getText();
This of course would return the first child element that matched the name
and contained the attribute.
Ideally this could be extended to support a multiple attribute list.
Thanks
-Dave
_______________________________________________
To control your jdom-interest membership:
http://lists.denveronline.net/mailman/options/jdom-interest/youraddr@yourhos
t.com
More information about the jdom-interest
mailing list