开发者

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

开发者 https://www.devze.com 2023-04-12 21:54 出处:网络
I am reading an XML using dom4j by using XPath techniques for selecting desired nodes. Consider that my XML looks like this:

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.sele开发者_如何学运维ctNodes("//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");


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消