-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSolution.java
More file actions
93 lines (72 loc) · 2.65 KB
/
Solution.java
File metadata and controls
93 lines (72 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//And the devil that deceived them was cast into the lake of fire and brimstone, where the beast and the false prophet are, and shall be tormented day and night for ever and ever. (Revelation 20:10)
package com.javarush.task.task33.task3306;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.IOException;
import java.io.StringWriter;
/*
Первая сериализация в XML
*/
public class Solution {
public static void main(String[] args) throws IOException, JAXBException {
Cat cat = new Cat();
cat.name = "Murka";
cat.age = 5;
cat.weight = 3;
Dog dog = new Dog();
dog.name = "Killer";
dog.age = 8;
dog.owner = "Bill Jeferson";
StringWriter writer = new StringWriter();
convertToXml(writer, cat);
convertToXml(writer, dog);
System.out.println(writer.toString());
/* expected output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cat>
<name>Murka</name>
<age>5</age>
<weight>3</weight>
</cat>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dog>
<name>Killer</name>
<age>8</age>
<owner>Bill Jeferson</owner>
</dog>
*/
}
public static void convertToXml(StringWriter writer, Object obj) throws IOException, JAXBException {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(obj, writer);
}
public static class Pet {
public String name;
}
@XmlType(name="cat")
@XmlRootElement
public static class Cat extends Pet {
public int age;
public int weight;
}
@XmlType(name="dog")
@XmlRootElement
public static class Dog extends Pet {
public int age;
public String owner;
}
}
/*
Первая сериализация в XML
Расставь правильно JAXB аннотации у статических классов.
Требования:
1. Класс Cat должен быть отмечен аннотацией @XmlRootElement.
2. Класс Cat должен быть отмечен аннотацией @XmlType с параметром name = "cat".
3. Класс Dog должен быть отмечен аннотацией @XmlRootElement.
4. Класс Dog должен быть отмечен аннотацией @XmlType с параметром name = "dog".
*/