Created
November 26, 2025 05:56
-
-
Save untainsYD/6fe823ef577fb82991559c7ede25769f to your computer and use it in GitHub Desktop.
Java advanced: Laboratory 3, Task5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package ua.inf.iwanoff.java.advanced.lab3; | |
| import ua.inf.iwanoff.java.advanced.lab3.service.DomManager; | |
| import ua.inf.iwanoff.java.advanced.lab3.service.StudentSaxHandler; | |
| import javax.xml.parsers.SAXParser; | |
| import javax.xml.parsers.SAXParserFactory; | |
| import java.io.File; | |
| import java.io.FileWriter; | |
| import java.io.IOException; | |
| import java.nio.file.Files; | |
| import java.nio.file.Paths; | |
| /** | |
| * Завдання 1.6: Використання SAX та DOM. | |
| */ | |
| public class Task5 { | |
| public static void main(String[] args) { | |
| System.out.println("=== Лабораторна робота 3. Завдання 1.6 (SAX & DOM) ==="); | |
| String sourceFile = "results/students_source.xml"; | |
| String modifiedFile = "results/students_modified.xml"; | |
| try { | |
| Files.createDirectories(Paths.get("results")); | |
| // 1. Створення тестового XML | |
| createSampleXml(sourceFile); | |
| System.out.println("Створено тестовий файл: " + sourceFile); | |
| // 2. SAX (Читання) | |
| System.out.println("\n--- 1. SAX Parser (Читання) ---"); | |
| SAXParserFactory factory = SAXParserFactory.newInstance(); | |
| SAXParser saxParser = factory.newSAXParser(); | |
| saxParser.parse(new File(sourceFile), new StudentSaxHandler()); | |
| // 3. DOM (Модифікація) | |
| System.out.println("\n--- 2. DOM Parser (Модифікація) ---"); | |
| DomManager.modifyXml(sourceFile, modifiedFile); | |
| // Перевірка результату модифікації через SAX | |
| System.out.println("\n--- Перевірка модифікованого файлу (через SAX) ---"); | |
| saxParser.parse(new File(modifiedFile), new StudentSaxHandler()); | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| private static void createSampleXml(String filename) throws IOException { | |
| String xmlContent = """ | |
| <?xml version="1.0" encoding="UTF-8" standalone="no"?> | |
| <Group> | |
| <GroupName>KN-224</GroupName> | |
| <Students> | |
| <Student id="1"> | |
| <Name>Ivanov Ivan</Name> | |
| <Age>20</Age> | |
| <Grade>85.5</Grade> | |
| </Student> | |
| <Student id="2"> | |
| <Name>Petrov Petro</Name> | |
| <Age>21</Age> | |
| <Grade>92.0</Grade> | |
| </Student> | |
| </Students> | |
| </Group> | |
| """; | |
| try (FileWriter writer = new FileWriter(filename)) { | |
| writer.write(xmlContent); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment