I need to parse XML file, output. I know how to handle the simplest ones, but I don't know what to do in case an unknown amount of elements in other elements using DOM parser. Example:
<server>
<users id="1">
<no id="106">
<name>Pat</name>
<email>p@exemple.com</email>
</no>
<no id="554">
<name>Bon</name>
<email>b@example.com</email>
</no>
</users>
<users id="2">
<no id="612">
...
...
I know how to print all 'no' elements, but I must separate them. Mainly, I must specify in output to which 'user' element these 'no' elements belong. Maybe there is a method which counts elements contained in another element with a specified argument ('id' in 'users'). Thank You.
Actually, I want to output:
Root Element: server
Pack of users: 1
Current Element: no
User no: 106
Name: Pat
E-mail: p@exemple.com
Current Element: no
User no: 554
Name: Bon
E-mail: b@exemple.com
Pack of users: 2
User no: 612
Name: ...
...
Just assign the unknown number of elements to a List<Node>
variable and iterate over it:
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
class Users {
public static void main (String... args) {
try {
Document dom = new SAXReader().read(new File(args[0]));
System.out.println("Root element: server\n");
List<Node> packs = dom.selectNodes("/server/users");
for (Node pack : packs) {
System.out.println("Pack of users: " + pack.valueOf("@id") + "\n");
List<Node> users = pack.selectNodes("no");
for (Node user : users) {
System.out.println("Current element: no");
System.out.println("User no: " + user.valueOf("@id"));
System.out.println("Name: " + user.valueOf("name"));
System.out.println("E-mail: " + user.valueOf("email") + "\n");
}
}
} catch (Throwable e) {
System.out.println(e);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.