FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaExercises/Experiments/Map2Xml.java at master · biblelamp/JavaExercises · GitHub
biblelamp
/
JavaExercises
Public
Notifications
You must be signed in to change notification settings
Fork
130
Star
153
Code
Issues
1
Pull requests
9
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaExercises
/
Experiments
/
Map2Xml.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
64 lines (60 loc) · 2.24 KB
Breadcrumbs
JavaExercises
/
Experiments
/
Map2Xml.java
Copy path
File metadata and controls
64 lines (60 loc) · 2.24 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
// @see http://technojeeves.com/index.php/54-serialize-a-java-collection-with-the-streaming-api
import
javax
.
xml
.
stream
.*;
import
java
.
io
.*;
import
java
.
util
.*;
public
class
Map2Xml
{
public
static
void
main
(
String
[]
args
) {
Map
<
String
,
Integer
>
m
=
Map2Xml
.
createRandomMap
();
System
.
out
.
println
(
"Starting map:"
);
System
.
out
.
println
(
m
);
// Now write it as xml
try
{
Map2Xml
.
toXml
(
m
,
new
FileWriter
(
"map2xml.xml"
));
}
catch
(
IOException
e
) {
e
.
printStackTrace
();
}
catch
(
XMLStreamException
e
) {
e
.
printStackTrace
();
}
}
public
static
Map
<
String
,
Integer
>
createRandomMap
() {
Map
<
String
,
Integer
>
m
=
new
HashMap
<
String
,
Integer
>(
5
);
for
(
char
i
=
'a'
;
i
<
'f'
;
i
++) {
m
.
put
(
String
.
valueOf
(
i
), (
int
)(
Math
.
random
() *
99
));
}
return
m
;
}
public
static
<
K
,
V
>
void
toXml
(
Map
<
K
,
V
>
map
,
Writer
out
)
throws
IOException
,
XMLStreamException
{
XMLStreamWriter
xsw
=
null
;
try
{
try
{
XMLOutputFactory
xof
=
XMLOutputFactory
.
newInstance
();
// If you want pretty-printing, you can use:
//xsw = new javanet.staxutils.IndentingXMLStreamWriter(xof.createXMLStreamWriter(out));
xsw
=
xof
.
createXMLStreamWriter
(
out
);
//xsw.writeStartDocument("utf-8", "1.0");
xsw
.
writeStartElement
(
"entries"
);
// Do the Collection
for
(
Map
.
Entry
<
K
,
V
>
e
:
map
.
entrySet
()) {
xsw
.
writeStartElement
(
"entry"
);
xsw
.
writeAttribute
(
"key"
,
e
.
getKey
().
toString
());
xsw
.
writeAttribute
(
"value"
,
e
.
getValue
().
toString
());
xsw
.
writeEndElement
();
}
xsw
.
writeEndElement
();
xsw
.
writeEndDocument
();
}
finally
{
if
(
out
!=
null
) {
try
{
out
.
close
() ; }
catch
(
IOException
e
) {
/* ignore */
}
}
}
// end inner finally
}
finally
{
if
(
xsw
!=
null
) {
try
{
xsw
.
close
() ; }
catch
(
XMLStreamException
e
) {
/* ignore */
}
}
}
}
}
Back
|
FazBrowse Home
|
New Git URL