/
akupan2012
/
XMLtoJONS
Обзор
Документация
Войти
/
akupan2012
/
XMLtoJONS
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Main.java
123 строки
4 KB
akupan2012
upload files
25 фев 2026, 21:56
Верифицирован
25 фев 2026, 21:56
4ca840b
Код
Авторство
О чём код?
import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Employee> list = parseXML("data.xml"); String json = listToJson(list); writeString(json, "data2.json"); System.out.println("Программа успешно завершена!"); } public static List<Employee> parseXML(String fileName) { List<Employee> employees = new ArrayList<>(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File(fileName)); Element root = document.getDocumentElement(); NodeList nodeList = root.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals("employee")) { Element employeeElement = (Element) node; int id = Integer.parseInt(getTagValue(employeeElement, "id")); String firstName = getTagValue(employeeElement, "firstName"); String lastName = getTagValue(employeeElement, "lastName"); String country = getTagValue(employeeElement, "country"); int age = Integer.parseInt(getTagValue(employeeElement, "age")); Employee employee = new Employee(id, firstName, lastName, country, age); employees.add(employee); System.out.println("Найден сотрудник: " + employee); } } } catch (ParserConfigurationException | SAXException | IOException e) { System.out.println("Ошибка при парсинге XML: " + e.getMessage()); e.printStackTrace(); } return employees; } private static String getTagValue(Element element, String tagName) { NodeList nodeList = element.getElementsByTagName(tagName); if (nodeList.getLength() > 0) { Node node = nodeList.item(0); return node.getTextContent(); } return ""; } public static String listToJson(List<Employee> list) { StringBuilder json = new StringBuilder(); json.append("[\n"); for (int i = 0; i < list.size(); i++) { Employee emp = list.get(i); json.append(" {\n"); json.append(" \"id\": ").append(emp.getId()).append(",\n"); json.append(" \"firstName\": \"").append(emp.getFirstName()).append("\",\n"); json.append(" \"lastName\": \"").append(emp.getLastName()).append("\",\n"); json.append(" \"country\": \"").append(emp.getCountry()).append("\",\n"); json.append(" \"age\": ").append(emp.getAge()).append("\n"); json.append(" }"); if (i < list.size() - 1) { json.append(","); } json.append("\n"); } json.append("]"); return json.toString(); } public static void writeString(String json, String fileName) { try (FileWriter writer = new FileWriter(fileName)) { writer.write(json); System.out.println("JSON успешно записан в файл " + fileName); } catch (IOException e) { System.out.println("Ошибка при записи файла: " + e.getMessage()); e.printStackTrace(); } } }