ChanGan
ChanGan

Reputation: 4318

How to get the element from the xml using Xpath Java

<employees>
    <employee>
        <firstName>Lokesh</firstName>
        <lastName>Gupta</lastName>
        <department>
            <id>101</id>
            <name>IT</name>
        </department>
    </employee>
</employees>

I wanted to get the elements name using Xpath..

I need to count the number of elements that i am getting using count(//employees/*) and count(//employees/employee/department/*)

it is returning count of each parent..

I need to get the element names as well //employees/employee/*/name() to get the elements name FirstName, LastName and Department..

also (//employees/employee/department/*/name()) to return name and id.. but it is showing error javax.xml.transform.TransformerException: Unknown nodetype: name .

Upvotes: 0

Views: 488

Answers (1)

E.Wiest
E.Wiest

Reputation: 5905

You want to get the elements names (not the value of it). name() has to appear the first. Since javax only supports XPath 1.0, you can use :

concat(name(//employees/employee/*[1]),",",name(//employees/employee/*[2]),",",name(//employees/employee/*[3]))

Output : firstName,lastName,department

concat(name(//employees/employee/department/*[1]),",",name(//employees/employee/department/*[2]))

Output : id,name

If you don't know the number of child for each parent element, you should use a loop approach. First, count and store the number of child (count(//employees/employee/*)), then make a loop where you increase the position index ([i]) at each iteration //employees/employee/*[i] i=i+1.

Upvotes: 1

Related Questions