11
WORK WITH XML-files in Java Для студентов старших курсов университетов Ст.преподаватель Дудник

Work with xml in java

Embed Size (px)

Citation preview

Page 1: Work with xml in java

WORK WITH XML-files in Java

Для студентов

старших курсов университетов

Ст.преподаватель Дудник О.А.

Page 2: Work with xml in java

• XML-eXtensible Markup Language(расширяемыXй язык

разметок)

Page 3: Work with xml in java

• XML-файлы можно использовать в качестве базы данных.

• Для чтения и записи в такие файлы в Java используется библиотека JAXB.

• Для ее подключения нужно дописать• import

javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlRootElement;

Page 4: Work with xml in java

• File: employee.xml

• <?xml version="1.0" encoding="UTF-8" standalone="yes"?>  

• <employee id="1">  

•     <name>Vimal Jaiswal</name>  

•     <salary>50000.0</salary>  

• </employee>  

Page 5: Work with xml in java

• Как сгенерировать этот файл?• File: ObjectToXml.java• import java.io.FileOutputStream;  •   • import javax.xml.bind.JAXBContext;  • import javax.xml.bind.Marshaller;  •   •   • public class ObjectToXml {  • public static void main(String[] args) throws Exception{  •     JAXBContext contextObj = JAXBContext.newInstance(Employee.class);  •   •     Marshaller marshallerObj = contextObj.createMarshaller();  •     marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  •   •     Employee emp1=new Employee(1,"Vimal Jaiswal",50000);  •       •     marshallerObj.marshal(emp1, new FileOutputStream("employee.xml"));  •        • }  • }  

Page 6: Work with xml in java

• File: Employee.java• import javax.xml.bind.annotation.XmlAttribute;  • import javax.xml.bind.annotation.XmlElement;  • import javax.xml.bind.annotation.XmlRootElement;  •   • @XmlRootElement  • public class Employee {  •     private int id;  •     private String name;  •     private float salary;  •   • public Employee() {}  • public Employee(int id, String name, float salary) {  •     super();  •     this.id = id;  •     this.name = name;  •     this.salary = salary;  • }  • @XmlAttribute  • public int getId() {  •     return id;  • }  • public void setId(int id) {  •     this.id = id;  • }  • @XmlElement  • public String getName() {  •     return name;  • }  • public void setName(String name) {  •     this.name = name;  • }  • @XmlElement  • public float getSalary() {  •     return salary;  • }  • public void setSalary(float salary) {  •     this.salary = salary;  • }  •   •   • } 

Page 7: Work with xml in java

• Рассмотрим еще пример XML-файла:• <?xml version="1.0" encoding="UTF-8"

standalone="yes"?><horseList> <horse> <horse_number>1</horse_number> <name_horse>That Darn Gray Cat</name_horse> <odds>5</odds> <did_win>lost</did_win> </horse> <horse> <horse_number>2</horse_number> <name_horse>Fort Utopia</name_horse> <odds>10</odds> <did_win>win</did_win> </horse>

• </horseList>

Page 8: Work with xml in java

• @XmlAccessorType(XmlAccessType.FIELD)@XmlRootElement( name ="horse" )

• public class Horse { public String horse_number; public String name_horse; public String odds; public String did_win;

public void setHorse_number(String horse_number) { this.horse_number = horse_number; }

public void setName_horse(String name_horse) { this.name_horse = name_horse; }

public void setOdds(String odds) { this.odds = odds; }

public void setDid_win(String did_win) { this.did_win = did_win; } public String getHorse_number() { return horse_number; } public String getName_horse() { return name_horse; } public String getOdds() { return odds; } public String getDid_win() { return did_win; }}

Page 9: Work with xml in java

• @XmlAccessorType(XmlAccessType.FIELD)@XmlRootElement( name ="horseList" )public class HorseList {

@XmlElement( name = "horse", type =Horse.class ) private List<Horse> horseList =new ArrayList<Horse>(); public HorseList(){}

public HorseList(List<Horse> horseList){ this.horseList = horseList; }

public List<Horse> getHorseList() { return horseList; }

public void setHorseList(List<Horse> horseList) { this.horseList = horseList; }

// Export public static void marshal(List<Horse> ids, File selectedFile) throws IOException, JAXBException { JAXBContext context; BufferedWriter writer = null; writer = new BufferedWriter(new FileWriter(selectedFile)); context = JAXBContext.newInstance(HorseList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(new HorseList(ids), writer); writer.close(); }

// Import public static List<Horse> unmarshal(File importFile) throws JAXBException { HorseList ids = new HorseList();

JAXBContext context = JAXBContext.newInstance(HorseList.class); Unmarshaller um = context.createUnmarshaller(); ids = (HorseList) um.unmarshal(importFile);

return ids.getHorseList(); }}

Page 10: Work with xml in java
Page 11: Work with xml in java

• УСПЕХОВ!