แปลง XML กลับมาเป็น Object ใน Java

แปลง XML กลับมาเป็น Object ใน Java

แปลง Object เป็น XML -> https://iotnoob.com/wordpress/2025/08/16/create-xml-file-from-object-in-java/

ทีนี้ ในทางกลับกัน เราก็แปลงกลับได้เหมือนกัน

ตัวอย่างนี้จะยังไม่ใช้ XSD เพื่อ verify XML ว่า format ถูกต้องหรือไม่

    private static void readAndVerifyXml() {
        try {
            // 1. สร้าง JAXB Context จาก Class ที่ต้องการ
            JAXBContext context = JAXBContext.newInstance(StackRootCollection.class);

            // 2. สร้าง Unmarshaller (ตัวแปลง XML เป็น Object)
            Unmarshaller unmarshaller = context.createUnmarshaller();

            File xmlFile = new File("C:\\tmp\\resultxxx.stkx");

            // 6. ทำการ Unmarshal (แปลงไฟล์ XML เป็น Object)
            // หาก XML ไม่ตรงตาม XSD, JAXBException จะถูกโยนออกมาตรงนี้
            StackRootCollection customer = (StackRootCollection) unmarshaller.unmarshal(xmlFile);

            // ถ้าสำเร็จ แสดงผลลัพธ์
            System.out.println("✅ Success! XML is valid and parsed correctly.");
            System.out.println("Resulting object: " + customer);

        } catch (JAXBException e) {
            // ถ้าไม่สำเร็จ (เช่น XML ผิดโครงสร้าง)
            System.out.println("❌ Error! XML is invalid or does not match the XSD schema.");
            System.err.println("Error Details: " + e.getMessage());
        } catch (Exception e) {
            // จัดการ Exception อื่นๆ ที่อาจเกิดขึ้น
            System.err.println("An unexpected error occurred: " + e.getMessage());
        }
    }