3

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.

2 Answers2

3

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");
Benson Kiprono
  • 129
  • 1
  • 1
  • 12
borjab
  • 11,149
  • 6
  • 71
  • 98
  • 1
    I searched all over the internet for such a solution and was getting frustrated until I landed here. This should be an accepted answer. That . (dot) ensures that fetched elements are children of the current node. Thank you @borjab – Benson Kiprono Jul 10 '22 at 14:41
0

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

Emircan
  • 1
  • 1