0

I want to get the number of elements in an xml, which have specific name eg. name="while")

The problem is that if I use the following code- I only get top level elements that have this name--

       for ( Iterator i = root.elementIterator( "while" ); i.hasNext(); ) {
            Element foo = (Element) i.next();

But any lower level "while" element is not part of the iterator...

What is the most efficient way of obtaining all elements (whether top level or lower level) that have name="while"? Do I have to parse through all elements in document for this purpose?

Arvind
  • 6,404
  • 20
  • 94
  • 143
  • Can't you use [element.getElementsByTagName(String)](http://dom4j.sourceforge.net/dom4j-1.6.1/apidocs/org/dom4j/dom/DOMElement.html#getElementsByTagName%28java.lang.String%29)? I'm pretty sure that gave me all elements with that name. Something that I didn't want. – TikkaBhuna Jun 11 '12 at 14:19

3 Answers3

1

You can use XPath for that using //while or the name() function and a wildcard node *: //*[name() = 'while']

List list = document.selectNodes("//*[name() = 'while']"); // or "//while"
int numberOfNodes = list.size();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
    // do something
}
Alex
  • 25,147
  • 6
  • 59
  • 55
  • how do I first verify if there is any element with name=while in the document? – Arvind Jun 11 '12 at 13:54
  • You just need to call `size()` on the List that holds the `while` nodes. – Alex Jun 11 '12 at 14:04
  • I tried using your code- this is the error I am getting-- Exception in thread "main" java.lang.NoClassDefFoundError: org/jaxen/JaxenException at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230) at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207) at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164) at Test.processwhile(Test.java:70) --- Kindly clarify on what went wrong...Am I missing something here? Thanks... – Arvind Jun 11 '12 at 15:12
  • You are missing some dependencies or you have not configured your classpath correctly. `org/jaxen/JaxenException` is bundled with `dom4j` – Alex Jun 11 '12 at 16:44
1

This regex worked for me:

document.selectNodes(".//*")
JAL
  • 41,701
  • 23
  • 172
  • 300
0

Element Iterator works only for next level in xPath. To be able to parse all XML and get all Element you have to use some recursion. For example next code will return list of all nodes with "name"

public List<Element> getElementsByName(String name, Element parent, List<Element> elementList)
{
    if (elementList == null)
        elementList = new ArrayList<Element>();

    for ( Iterator i = parent.elementIterator(); i.hasNext(); ) {
        Element current = (Element) i.next();
        if (current.getName().equalsIgnoreCase(name))
        {
            elementList.add(current);
        }

        getElementsByName(name, current, elementList);
    }
    return elementList;
}