Bài hướng dẫn này sẽ giúp bạn biết cách nhanh chóng tạo XML từ XSD trong Eclipse với các trường tùy chọn và giá trị mặc định, giúp bạn tập trung vào điều chỉnh dữ liệu cho các trường hợp kiểm thử cụ thể.

Tạo XML từ XSD trong Eclipse
Chỉ cần làm theo các bước dưới đây để tạo file XML từ file XSD trong Eclipse:
- Trong project, chọn file XSD, nhấn chuột phải để mở menu và chọn Generate > XML File…
- Trong cửa sổ hiện ra, điền tên và chọn vị trí lưu cho file XML. Sau đó, nhấn nút Next.
- Chọn root element (phần tử cấp cao nhất) mà bạn muốn dùng để tạo file XML mẫu. Hãy đảm bảo bạn đã tích chọn các ô Create optional attributes và Create optional elements. Giao diện chương trình sẽ trông như hình dưới đây.

- Nhấn nút Finish. Eclipse sẽ tạo ra một file XML với các giá trị mặc định. Sau đó bạn có thể thay đổi các giá trị này cho phù hợp với yêu cầu của mình.
Ví dụ chuyển đổi XSD sang XML
Dưới đây là file Employee.xsd mà ta sẽ dùng để tạo ra các file XML trong ví dụ này.
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="<https://www.w3.org/2001/XMLSchema>"
targetNamespace="<https://www.journaldev.com/Employee>"
xmlns:empns="<https://www.journaldev.com/Employee>" elementFormDefault="qualified">
<element name="empRequest" type="empns:empRequest"></element>
<element name="empResponse" type="empns:empResponse"></element>
<complexType name="empRequest">
<sequence>
<element name="id" type="int"></element>
</sequence>
</complexType>
<complexType name="empResponse">
<sequence>
<element name="id" type="int"></element>
<element name="role" type="string"></element>
<element name="fullName" type="string"></element>
</sequence>
</complexType>
</schema>
Vì XSD này có hai root element là empRequest và empResponse, ta có thể tạo ra hai file XML tương ứng. Dưới đây là các file XML do Eclipse tạo ra, với các giá trị đã được thay đổi.
EmployeeRequest.xml
<?xml version="1.0" encoding="UTF-8"?>
<empns:empRequest xmlns:empns="<https://www.journaldev.com/Employee>" xmlns:xsi="<https://www.w3.org/2001/XMLSchema-instance>" xsi:schemaLocation="<https://www.journaldev.com/Employee> Employee.xsd ">
<empns:id>5</empns:id>
</empns:empRequest>
EmployeeResponse.xml
<?xml version="1.0" encoding="UTF-8"?>
<empns:empResponse xmlns:empns="<https://www.journaldev.com/Employee>" xmlns:xsi="<https://www.w3.org/2001/XMLSchema-instance>" xsi:schemaLocation="<https://www.journaldev.com/Employee> Employee.xsd ">
<empns:id>1</empns:id>
<empns:role>Developer</empns:role>
<empns:fullName>Pankaj Kumar</empns:fullName>
</empns:empResponse>
Hy vọng mẹo nhỏ này sẽ giúp bạn tạo file XML từ XSD tương xứng một cách dễ dàng hơn.