dom4J: How to get the value of Elements of a Node?

10.2k Views Asked by At

I am reading an XML using dom4j by using XPath techniques for selecting desired nodes. Consider that my XML looks like this:

<Employees>
    <Emp id=1>
        <name>jame</name>
        <age>12</age>
    </Emp>
    .
    .
    .
</Employees> 

Now i need to store the Information of all employees in a list of my Employee Class. Until i code the following:

List<? extends Node> lstprmntEmps = document.selectNodes("//Employees/Emp");
ArrayList<Employee> Employees = new ArrayList<Employee>();//Employee is my custom class
for (Node node : lstprmntEmps)
{  
Employees.add(ParseEmployee(node));//ParseEmployee(. . .) is my custom function that pareses emp XML and return Employee object
}

Now how do i get the name and age of Currently selected Node? is there any such method exist node.getElementValue("name");

1

There are 1 best solutions below

0
On BEST ANSWER

Cast each node to Element, then ask the element for its first "name" sub-element and its first "age" sub-element and get their text.

See http://dom4j.sourceforge.net/apidocs/org/dom4j/Element.html.

The elementText(String) method of Element maybe gets a sub-element by name and retrieves its text in one operation, but it's undocumented, so it's hard to say.

Note that variables and methods should always start with a lowercase letter in Java.