Парсер JDOM2 может использоваться для чтения XML, разбора XML и записи XML-файлов после обновления его содержимого. Он сохраняет документы JDOM2 в памяти для чтения и изменения их значений. После загрузки XML-документа в память JDOM2 поддерживает строгие отношения типа родитель-потомок. Экземпляры JDOM родительского типа(родитель) имеют методы для доступа к своему содержимому, а экземпляры JDOM дочернего типа(содержимое) имеют методы для доступа к своему родителю.
Обратите внимание, что в этом руководстве мы использовали лямбда-выражения и ссылки на методы, поэтому нам необходимо настроить проект на использование Java версии не ниже 1.8.
1. Знаток
Включите в проект последнюю версию jdom2.
<dependency><groupId>org.jdom</groupId><artifactId>jdom2</artifactId><version>2.0.6.1</version></dependency>
Для выполнения XPath нам также понадобится jaxen.
<dependency><groupId>jaxen</groupId><artifactId>jaxen</artifactId><version>2.0.0</version></dependency>
2. Создать документ JDOM2
Мы можем создать экземпляр org.jdom2.Document, используя любой парсер, перечисленный ниже. Все они анализируют XML и возвращают документ JDOM2 в памяти.
2.1 Использование DOM-парсера
private static Document getDOMParsedDocument(final String fileName) {Document document = null;try {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//If want to make namespace aware.//factory.setNamespaceAware(true);DocumentBuilder documentBuilder = factory.newDocumentBuilder();org.w3c.dom.Document w3cDocument = documentBuilder.parse(fileName);document = new DOMBuilder().build(w3cDocument);}catch(IOException | SAXException | ParserConfigurationException e) {e.printStackTrace();}return document;}
2.2 Использование SAX-парсера
private static Document getSAXParsedDocument(final String fileName) {SAXBuilder builder = new SAXBuilder();Document document = null;try {document = builder.build(fileName);}catch(JDOMException | IOException e) {e.printStackTrace();}return document;}
2.3 Использование StAX Parser
private static Document getStAXParsedDocument(final String fileName) {Document document = null;try {XMLInputFactory factory = XMLInputFactory.newFactory();XMLEventReader reader = factory.createXMLEventReader(new FileReader(fileName));StAXEventBuilder builder = new StAXEventBuilder();document = builder.build(reader);}catch(JDOMException | IOException | XMLStreamException e) {e.printStackTrace();}return document;}
3. Чтение XML-контента
Мы будем читать следующий файл employees.xml.
<employees><employee id="101"><firstName>Lokesh</firstName><lastName>Gupta</lastName><country>India</country><department id="25"><name>ITS</name></department></employee><employee id="102"><firstName>Brian</firstName><lastName>Schultz</lastName><country>USA</country><department id="26"><name>DEV</name></department></employee></employees>
3.1 Корневой узел
Используйте метод document.getRootElement().
String xmlFile = "employees.xml";Document document = getSAXParsedDocument(xmlFile);Element rootNode = document.getRootElement();System.out.println("Root Element :: " + rootNode.getName());
Вывод программы:
Root Element :: employees
3.2 Значение атрибута
Используйте метод Element.getAttributeValue().
public static void main(String[] args) {String xmlFile = "employees.xml";Document document = getSAXParsedDocument(xmlFile);Element rootNode = document.getRootElement();rootNode.getChildren("employee").forEach( ReadXMLDemo::readEmployeeNode );}private static void readEmployeeNode(Element employeeNode) {//Employee IdSystem.out.println("Id : " + employeeNode.getAttributeValue("id"));}
Вывод программы:
Id : 101Id : 102
3.3 Значение элемента
Используйте методы Element.getChildText() или Element.getText().
public static void main(String[] args) {String xmlFile = "employees.xml";Document document = getSAXParsedDocument(xmlFile);Element rootNode = document.getRootElement();rootNode.getChildren("employee").forEach( ReadXMLDemo::readEmployeeNode );}private static void readEmployeeNode(Element employeeNode) {//Employee IdSystem.out.println("Id : " + employeeNode.getAttributeValue("id"));//First NameSystem.out.println("FirstName : " + employeeNode.getChildText("firstName"));//Last NameSystem.out.println("LastName : " + employeeNode.getChildText("lastName"));//CountrySystem.out.println("country : " + employeeNode.getChild("country").getText());/**Read Department Content*/employeeNode.getChildren("department").forEach( ReadXMLDemo::readDepartmentNode );}private static void readDepartmentNode(Element deptNode) {//Department IdSystem.out.println("Department Id : " + deptNode.getAttributeValue("id"));//Department NameSystem.out.println("Department Name : " + deptNode.getChildText("name"));}
Вывод программы:
FirstName : LokeshLastName : Guptacountry : IndiaDepartment Id : 25Department Name : ITSFirstName : BrianLastName : Schultzcountry : USADepartment Id : 26Department Name : DEV
4. Использование XPath
Чтобы прочитать любой набор значений элемента с помощью xpath, нам нужно скомпилировать XPathExpression и использовать его метод estimate().
String xmlFile = "employees.xml";Document document = getSAXParsedDocument(xmlFile);XPathFactory xpfac = XPathFactory.instance();//Read employee idsXPathExpression<Attribute> xPathA = xpfac.compile("//employees/employee/@id", Filters.attribute());for(Attribute att : xPathA.evaluate(document)) {System.out.println("Employee Ids :: " + att.getValue());}//Read employee first namesXPathExpression<Element> xPathN = xpfac.compile("//employees/employee/firstName", Filters.element());for(Element element : xPathN.evaluate(document)) {System.out.println("Employee First Name :: " + element.getValue());}
Вывод программы:
Employee Ids :: 101Employee Ids :: 102Employee First Name :: LokeshEmployee First Name :: Brian
5. Полный пример
Вот полный код для чтения XML с использованием JDOM2 в Java.
import java.io.FileReader;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.stream.XMLEventReader;import javax.xml.stream.XMLInputFactory;import javax.xml.stream.XMLStreamException;import org.jdom2.Attribute;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.filter.Filters;import org.jdom2.input.DOMBuilder;import org.jdom2.input.SAXBuilder;import org.jdom2.input.StAXEventBuilder;import org.jdom2.xpath.XPathExpression;import org.jdom2.xpath.XPathFactory;import org.xml.sax.SAXException;@SuppressWarnings("unused")public class ReadXMLDemo{public static void main(String[] args){String xmlFile = "employees.xml";Document document = getSAXParsedDocument(xmlFile);/**Read Document Content*/Element rootNode = document.getRootElement();System.out.println("Root Element :: " + rootNode.getName());System.out.println("\n=================================\n");/**Read Employee Content*/rootNode.getChildren("employee").forEach( ReadXMLDemo::readEmployeeNode );System.out.println("\n=================================\n");readByXPath(document);}private static void readEmployeeNode(Element employeeNode){//Employee IdSystem.out.println("Id : " + employeeNode.getAttributeValue("id"));//First NameSystem.out.println("FirstName : " + employeeNode.getChildText("firstName"));//Last NameSystem.out.println("LastName : " + employeeNode.getChildText("lastName"));//CountrySystem.out.println("country : " + employeeNode.getChild("country").getText());/**Read Department Content*/employeeNode.getChildren("department").forEach( ReadXMLDemo::readDepartmentNode );}private static void readDepartmentNode(Element deptNode){//Department IdSystem.out.println("Department Id : " + deptNode.getAttributeValue("id"));//Department NameSystem.out.println("Department Name : " + deptNode.getChildText("name"));}private static void readByXPath(Document document){//Read employee idsXPathFactory xpfac = XPathFactory.instance();XPathExpression<Attribute> xPathA = xpfac.compile("//employees/employee/@id", Filters.attribute());for(Attribute att : xPathA.evaluate(document)){System.out.println("Employee Ids :: " + att.getValue());}XPathExpression<Element> xPathN = xpfac.compile("//employees/employee/firstName", Filters.element());for(Element element : xPathN.evaluate(document)){System.out.println("Employee First Name :: " + element.getValue());}}private static Document getSAXParsedDocument(final String fileName){SAXBuilder builder = new SAXBuilder();Document document = null;try{document = builder.build(fileName);}catch(JDOMException | IOException e){e.printStackTrace();}return document;}private static Document getStAXParsedDocument(final String fileName){Document document = null;try{XMLInputFactory factory = XMLInputFactory.newFactory();XMLEventReader reader = factory.createXMLEventReader(new FileReader(fileName));StAXEventBuilder builder = new StAXEventBuilder();document = builder.build(reader);}catch(JDOMException | IOException | XMLStreamException e){e.printStackTrace();}return document;}private static Document getDOMParsedDocument(final String fileName){Document document = null;try{DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//If want to make namespace aware.//factory.setNamespaceAware(true);DocumentBuilder documentBuilder = factory.newDocumentBuilder();org.w3c.dom.Document w3cDocument = documentBuilder.parse(fileName);document = new DOMBuilder().build(w3cDocument);}catch(IOException | SAXException | ParserConfigurationException e){e.printStackTrace();}return document;}/*private static String readFileContent(String filePath){StringBuilder contentBuilder = new StringBuilder();try(Stream<String> stream = Files.lines( Paths.get(filePath), StandardCharsets.UTF_8)){stream.forEach(s -> contentBuilder.append(s).append("\n"));}catch(IOException e){e.printStackTrace();}return contentBuilder.toString();}*/}
Вывод программы:
Root Element :: employees=================================Id : 101FirstName : LokeshLastName : Guptacountry : IndiaDepartment Id : 25Department Name : ITSId : 102FirstName : BrianLastName : Schultzcountry : USADepartment Id : 26Department Name : DEV=================================Employee Ids :: 101Employee Ids :: 102Employee First Name :: LokeshEmployee First Name :: Brian