user3797234
user3797234

Reputation: 57

How to get nodes of only current element in dom4j?

Please help me to solve the following issue in dom4j

This is my xml file:

<root>
    <variant>
        <name>first</name>
        <values>
            <name>first_element</name>
        </values>
    </variant>
    <variant>
        <name>second</name>
        <values>
            <name>second_element</name>
        </values>
    </variant>
</root>

I used following java code to get the variant node.

root.selectNodes("\root\variant");

This is giving me the list count as 2. I am using list to collect each node individually. from list nodes I am iterating. I used to following code to get the value "values\name".

variant.selectNodes("\\values\name");

I am getting both the values "first_element and second_element". could any one help me to get one values of the current node.

Upvotes: 3

Views: 1829

Answers (2)

borjab
borjab

Reputation: 11655

As it uses XPath why don't you try something like:

root.selectNodes("/root/variant[1]/values/name");

This means: Take the first variant in root and search for "\values\name".

You may also try to remove the double slash. Double slash means any case that has an ancestor so it may be confusing. You may use the dot to select the current node:

variant.selectNodes("./values/name");

Upvotes: 3

Emircan
Emircan

Reputation: 1

You should select name from current node like this :

    List list = document.selectNodes( "//a/@href" );

    for (Iterator iter = list.iterator(); iter.hasNext(); ) {
        Attribute attribute = (Attribute) iter.next();
        String url = attribute.getValue();
    }

http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html

Upvotes: 0

Related Questions