1
|
|
|
#!/usr/bin/env python |
2
|
|
|
# encoding: utf-8 |
3
|
|
|
|
4
|
|
|
from xml.dom import minidom |
5
|
|
|
|
6
|
|
|
from .json_exporter import JSONExporter |
7
|
|
|
from .util import get_tags_count |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
class XMLExporter(JSONExporter): |
11
|
|
|
"""This Exporter can convert entries and journals into XML.""" |
12
|
|
|
|
13
|
|
|
names = ["xml"] |
14
|
|
|
extension = "xml" |
15
|
|
|
|
16
|
|
|
@classmethod |
17
|
|
|
def export_entry(cls, entry, doc=None): |
18
|
|
|
"""Returns an XML representation of a single entry.""" |
19
|
|
|
doc_el = doc or minidom.Document() |
20
|
|
|
entry_el = doc_el.createElement("entry") |
21
|
|
|
for key, value in cls.entry_to_dict(entry).items(): |
22
|
|
|
elem = doc_el.createElement(key) |
23
|
|
|
elem.appendChild(doc_el.createTextNode(value)) |
24
|
|
|
entry_el.appendChild(elem) |
25
|
|
|
if not doc: |
26
|
|
|
doc_el.appendChild(entry_el) |
27
|
|
|
return doc_el.toprettyxml() |
28
|
|
|
else: |
29
|
|
|
return entry_el |
30
|
|
|
|
31
|
|
|
@classmethod |
32
|
|
|
def entry_to_xml(cls, entry, doc): |
33
|
|
|
entry_el = doc.createElement("entry") |
34
|
|
|
entry_el.setAttribute("date", entry.date.isoformat()) |
35
|
|
|
if hasattr(entry, "uuid"): |
36
|
|
|
entry_el.setAttribute("uuid", entry.uuid) |
37
|
|
|
entry_el.setAttribute("starred", entry.starred) |
38
|
|
|
tags = entry.tags |
39
|
|
|
for tag in tags: |
40
|
|
|
tag_el = doc.createElement("tag") |
41
|
|
|
tag_el.setAttribute("name", tag) |
42
|
|
|
entry_el.appendChild(tag_el) |
43
|
|
|
entry_el.appendChild(doc.createTextNode(entry.fulltext)) |
44
|
|
|
return entry_el |
45
|
|
|
|
46
|
|
|
@classmethod |
47
|
|
|
def export_journal(cls, journal): |
48
|
|
|
"""Returns an XML representation of an entire journal.""" |
49
|
|
|
tags = get_tags_count(journal) |
50
|
|
|
doc = minidom.Document() |
51
|
|
|
xml = doc.createElement("journal") |
52
|
|
|
tags_el = doc.createElement("tags") |
53
|
|
|
entries_el = doc.createElement("entries") |
54
|
|
|
for count, tag in tags: |
55
|
|
|
tag_el = doc.createElement("tag") |
56
|
|
|
tag_el.setAttribute("name", tag) |
57
|
|
|
count_node = doc.createTextNode(str(count)) |
58
|
|
|
tag_el.appendChild(count_node) |
59
|
|
|
tags_el.appendChild(tag_el) |
60
|
|
|
for entry in journal.entries: |
61
|
|
|
entries_el.appendChild(cls.entry_to_xml(entry, doc)) |
62
|
|
|
xml.appendChild(entries_el) |
63
|
|
|
xml.appendChild(tags_el) |
64
|
|
|
doc.appendChild(xml) |
65
|
|
|
return doc.toprettyxml() |
66
|
|
|
|