|
| 1 | +package com.mkyong.xml.jdom; |
| 2 | + |
| 3 | +import org.jdom2.Document; |
| 4 | +import org.jdom2.Element; |
| 5 | +import org.jdom2.JDOMException; |
| 6 | +import org.jdom2.input.SAXBuilder; |
| 7 | + |
| 8 | +import java.io.File; |
| 9 | +import java.io.IOException; |
| 10 | +import java.util.List; |
| 11 | + |
| 12 | +// https://mkyong.com/java/how-to-read-xml-file-in-java-jdom-example/ |
| 13 | +public class ReadXmlJDomParser { |
| 14 | + |
| 15 | + private static final String FILENAME = "src/main/resources/staff.xml"; |
| 16 | + |
| 17 | + // https://github.com/hunterhacker/jdom/wiki/JDOM2-A-Primer |
| 18 | + public static void main(String[] args) { |
| 19 | + |
| 20 | + try { |
| 21 | + |
| 22 | + SAXBuilder sax = new SAXBuilder(); |
| 23 | + // XML is a local file |
| 24 | + Document doc = sax.build(new File(FILENAME)); |
| 25 | + |
| 26 | + Element rootNode = doc.getRootElement(); |
| 27 | + List<Element> list = rootNode.getChildren("staff"); |
| 28 | + |
| 29 | + for (Element target : list) { |
| 30 | + |
| 31 | + String id = target.getAttributeValue("id"); |
| 32 | + String name = target.getChildText("name"); |
| 33 | + String role = target.getChildText("role"); |
| 34 | + String salary = target.getChildText("salary"); |
| 35 | + String currency = ""; |
| 36 | + if (salary != null && salary.length() > 1) { |
| 37 | + // access attribute |
| 38 | + currency = target.getChild("salary").getAttributeValue("currency"); |
| 39 | + } |
| 40 | + String bio = target.getChildText("bio"); |
| 41 | + |
| 42 | + System.out.printf("Staff id : %s%n", id); |
| 43 | + System.out.printf("Name : %s%n", name); |
| 44 | + System.out.printf("Role : %s%n", role); |
| 45 | + System.out.printf("Salary [Currency] : %,.2f [%s]%n", Float.parseFloat(salary), currency); |
| 46 | + System.out.printf("Bio : %s%n%n", bio); |
| 47 | + |
| 48 | + } |
| 49 | + |
| 50 | + } catch (IOException | JDOMException e) { |
| 51 | + e.printStackTrace(); |
| 52 | + } |
| 53 | + |
| 54 | + } |
| 55 | +} |
0 commit comments