SlideShare a Scribd company logo
1 of 11
WORK WITH XML-files in
Java
Для студентов
старших курсов университетов
Ст.преподаватель Дудник О.А.
• XML-eXtensible Markup
Language(расширяемыXй язык
разметок)
• XML-файлы можно использовать в
.качестве базы данных
• Для чтения и записи в такие файлы в
Java используется библиотека JAXB.
• Для ее подключения нужно дописать
• import
javax.xml.bind.annotation.XmlAccessType;
import
javax.xml.bind.annotation.XmlAccessorType;
import
javax.xml.bind.annotation.XmlRootElement;
• File: employee.xml
• <?xml version="1.0" encoding="UTF-
8" standalone="yes"?>
• <employee id="1">
• <name>Vimal Jaiswal</name>
• <salary>50000.0</salary>
• </employee>
• Как сгенерировать этот файл?
• 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"));  
•        
• }  
• }  
• 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;  
• Рассмотрим еще пример 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>
• @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;
• @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
• УСПЕХОВ!

More Related Content

What's hot

What's hot (9)

BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBCBI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
ORM Methodology
ORM MethodologyORM Methodology
ORM Methodology
 
Css
CssCss
Css
 
Project First presentation about introduction to technologies to be used
Project First presentation about introduction to technologies to be usedProject First presentation about introduction to technologies to be used
Project First presentation about introduction to technologies to be used
 
Java for XPages Development
Java for XPages DevelopmentJava for XPages Development
Java for XPages Development
 
Introduce to XML
Introduce to XMLIntroduce to XML
Introduce to XML
 
itPage LDC 09 Presentation
itPage LDC 09 PresentationitPage LDC 09 Presentation
itPage LDC 09 Presentation
 
Day 2 - Intro to Rails
Day 2 - Intro to RailsDay 2 - Intro to Rails
Day 2 - Intro to Rails
 

Viewers also liked

лекция 01 прогр на java (тсн) - введение в java
лекция 01   прогр на java (тсн) - введение в javaлекция 01   прогр на java (тсн) - введение в java
лекция 01 прогр на java (тсн) - введение в java
Sergey Talipov
 

Viewers also liked (7)

Java.fundamentals
Java.fundamentalsJava.fundamentals
Java.fundamentals
 
Oracle database
Oracle databaseOracle database
Oracle database
 
JPHP
JPHPJPHP
JPHP
 
Get started with docker &amp; dev ops
Get started with docker &amp; dev opsGet started with docker &amp; dev ops
Get started with docker &amp; dev ops
 
Jdbc in java
Jdbc in javaJdbc in java
Jdbc in java
 
лекция 01 прогр на java (тсн) - введение в java
лекция 01   прогр на java (тсн) - введение в javaлекция 01   прогр на java (тсн) - введение в java
лекция 01 прогр на java (тсн) - введение в java
 
JIT-компиляция в виртуальной машине Java (HighLoad++ 2013)
JIT-компиляция в виртуальной машине Java (HighLoad++ 2013)JIT-компиляция в виртуальной машине Java (HighLoad++ 2013)
JIT-компиляция в виртуальной машине Java (HighLoad++ 2013)
 

Similar to Work with xml in java

Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalacheIasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
Codecamp Romania
 
Solr Application Development Tutorial
Solr Application Development TutorialSolr Application Development Tutorial
Solr Application Development Tutorial
Erik Hatcher
 
Lecture 19 dynamic web - java - part 1
Lecture 19   dynamic web - java - part 1Lecture 19   dynamic web - java - part 1
Lecture 19 dynamic web - java - part 1
Д. Ганаа
 

Similar to Work with xml in java (20)

Hibernate&ejb3 . part3.
Hibernate&ejb3 . part3.Hibernate&ejb3 . part3.
Hibernate&ejb3 . part3.
 
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalacheIasi code camp 12 october 2013   jax-rs-jee-ecosystem - catalin mihalache
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
 
Approaches to document/report generation
Approaches to document/report generation Approaches to document/report generation
Approaches to document/report generation
 
Java architecture for xml binding
Java architecture for xml bindingJava architecture for xml binding
Java architecture for xml binding
 
AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdf
 
CRUD Operation of images through XML
CRUD Operation of images through XMLCRUD Operation of images through XML
CRUD Operation of images through XML
 
OpenNTF Webinar 2022-08 - XPages Jakarta EE Support in Practice
OpenNTF Webinar 2022-08 - XPages Jakarta EE Support in PracticeOpenNTF Webinar 2022-08 - XPages Jakarta EE Support in Practice
OpenNTF Webinar 2022-08 - XPages Jakarta EE Support in Practice
 
JAXB
JAXBJAXB
JAXB
 
Java
JavaJava
Java
 
java01.pdf
java01.pdfjava01.pdf
java01.pdf
 
XML parsing using jaxb
XML parsing using jaxbXML parsing using jaxb
XML parsing using jaxb
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Solr Application Development Tutorial
Solr Application Development TutorialSolr Application Development Tutorial
Solr Application Development Tutorial
 
Lecture 19 dynamic web - java - part 1
Lecture 19   dynamic web - java - part 1Lecture 19   dynamic web - java - part 1
Lecture 19 dynamic web - java - part 1
 
Java01
Java01Java01
Java01
 
Java01
Java01Java01
Java01
 
Java intro
Java introJava intro
Java intro
 
Java
JavaJava
Java
 
java01.ppt
java01.pptjava01.ppt
java01.ppt
 
java01.ppt
java01.pptjava01.ppt
java01.ppt
 

More from Asya Dudnik

использование Hibernate java persistence.part 4.
использование Hibernate java persistence.part 4.использование Hibernate java persistence.part 4.
использование Hibernate java persistence.part 4.
Asya Dudnik
 
использование Hibernate java persistence.part 2.
использование Hibernate java persistence.part 2.использование Hibernate java persistence.part 2.
использование Hibernate java persistence.part 2.
Asya Dudnik
 
Threads in java
Threads in javaThreads in java
Threads in java
Asya Dudnik
 
Usage concurrence in java
Usage concurrence in javaUsage concurrence in java
Usage concurrence in java
Asya Dudnik
 

More from Asya Dudnik (20)

Get started with docker &amp; dev ops
Get started with docker &amp; dev opsGet started with docker &amp; dev ops
Get started with docker &amp; dev ops
 
Work with my_sql_-_database_in_java
Work with my_sql_-_database_in_javaWork with my_sql_-_database_in_java
Work with my_sql_-_database_in_java
 
Java.fundamentals
Java.fundamentalsJava.fundamentals
Java.fundamentals
 
Data bases in pictures
Data bases in picturesData bases in pictures
Data bases in pictures
 
использование Hibernate java persistence.part 4.
использование Hibernate java persistence.part 4.использование Hibernate java persistence.part 4.
использование Hibernate java persistence.part 4.
 
использование Hibernate java persistence.part 2.
использование Hibernate java persistence.part 2.использование Hibernate java persistence.part 2.
использование Hibernate java persistence.part 2.
 
Work with my sql database in java
Work with my sql   database in javaWork with my sql   database in java
Work with my sql database in java
 
Web&java. gwt
Web&java. gwtWeb&java. gwt
Web&java. gwt
 
Web&java.jsf.
Web&java.jsf.Web&java.jsf.
Web&java.jsf.
 
Web&java. jsp
Web&java. jspWeb&java. jsp
Web&java. jsp
 
Web&java. jsp
Web&java. jspWeb&java. jsp
Web&java. jsp
 
Java fx for interface
Java fx for interfaceJava fx for interface
Java fx for interface
 
Java fx for interface
Java fx for interfaceJava fx for interface
Java fx for interface
 
Apache maven in java projects
Apache maven in java projectsApache maven in java projects
Apache maven in java projects
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Ejb in java. part 1.
Ejb in java. part 1.Ejb in java. part 1.
Ejb in java. part 1.
 
Work with xml in java
Work with xml in javaWork with xml in java
Work with xml in java
 
использование Hibernate java persistence.part 1.
использование Hibernate java persistence.part 1.использование Hibernate java persistence.part 1.
использование Hibernate java persistence.part 1.
 
Usage concurrence in java
Usage concurrence in javaUsage concurrence in java
Usage concurrence in java
 
Work with UML
Work with UMLWork with UML
Work with UML
 

Recently uploaded

QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 

Work with xml in java

  • 1. WORK WITH XML-files in Java Для студентов старших курсов университетов Ст.преподаватель Дудник О.А.
  • 3. • XML-файлы можно использовать в .качестве базы данных • Для чтения и записи в такие файлы в Java используется библиотека JAXB. • Для ее подключения нужно дописать • import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement;
  • 4. • File: employee.xml • <?xml version="1.0" encoding="UTF- 8" standalone="yes"?> • <employee id="1"> • <name>Vimal Jaiswal</name> • <salary>50000.0</salary> • </employee>
  • 5. • Как сгенерировать этот файл? • 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"));   •         • }   • }  
  • 6. • 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;  
  • 7. • Рассмотрим еще пример 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>
  • 8. • @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;
  • 9. • @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
  • 10.