Debian Codegraph @

gavo/grammars/xmlgrammar.py

raw
1 """
2 A grammar for generic XML documents.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 from lxml import etree
12
13 from gavo import base
14 from gavo.grammars.common import Grammar, RowIterator
15
16 def iterEventsCounting(inputFile, normalizeWhitespace):
17 """wraps etree.iterparse so [ct] elements are appended to element names
18 when they are repeated.
19
20 This currently takes some pains to strip namespaces, which probably just
21 uglify the keys in almost all applications I can see for this.
22 """
23 curPath = []
24 seenTags = [{}]
25 contentStack = [[]]
26
27 for action, elem in etree.iterparse(
28 inputFile,
29 events=("start", "end"),
30 remove_blank_text=normalizeWhitespace):
31 curTag = elem.tag
32 if curTag.startswith('{'):
33 curTag = curTag[curTag.index('}')+1:]
34
35 if action=="start":
36 if curTag in seenTags[-1]:
37 curPath.append("%s[%d]"%(curTag, seenTags[-1][curTag]))
38 seenTags[-1][curTag] += 1
39 else:
40 curPath.append(curTag)
41 seenTags[-1][curTag] = 0
42 seenTags.append({})
43 contentStack.append([])
44
45 elif action=="end":
46 if elem.text is not None:
47 contentStack[-1][:0] = [elem.text]
48 content = "".join(contentStack.pop()) or None
49 if content and normalizeWhitespace:
50 content = " ".join(content.split()) or None
51
52 basePath = "/".join(curPath)
53 yield basePath, content
54
55 for key, value in list(elem.items()):
56 yield basePath+"/@"+key, value
57
58 if elem.tail is not None:
59 contentStack[-1].append(elem.tail)
60 curPath.pop()
61 seenTags.pop()
62
63
64 class XMLRowIterator(RowIterator):
65 """an iterator for XMLGrammars.
66 """
67 def _iterRows(self):
68 if hasattr(self.sourceToken, "read"):
69 f, keepopen = self.sourceToken, True
70 else:
71 f, keepopen = open(self.sourceToken, "rb"), False
72
73 try:
74 yield dict(iterEventsCounting(
75 f,
76 self.grammar.normalizeWhitespace))
77 except etree.LxmlSyntaxError as ex:
78 raise base.SourceParseError(
79 ex.msg,
80 location=ex.position,
81 source=ex.filename)
82 finally:
83 if not keepopen:
84 f.close()
85
86
87 class XMLGrammar(Grammar):
88 """A grammar parsing from generic XML files.
89
90 Use this grammar to parse from generic XML files. For now, one rawdict
91 per document is returned (later extensions might let you define elements
92 that will yield rows).
93
94 The keys are xpaths (e.g., root/element or root/element/@attr), the values
95 the (joined) text nodes that are immediate children or the element.
96
97 When elements are repeated within an element, [ct] is appended to the path
98 element (e.g., root/element([0]).
99
100 For now, this grammar ignores namespaces.
101
102 Because most of the keys are not valid python identifiers, you cannot
103 use the @key syntax when mapping this. Use vars[key] instead (or
104 <map key="dest" source="path"/>).
105
106 Do not use this for VOTables; use VOTableGrammar instead.
107 """
108 name_ = "xmlGrammar"
109
110 _nsw = base.BooleanAttribute("normalizeWhitespace",
111 description="By default, the parser will return whitespace-only"
112 " content as None and will turn internal whitespace to a single"
113 " blank. Set this to False to preserve whitespace as present"
114 " in the document.",
115 default=True,
116 copyable=True)
117 rowIterator = XMLRowIterator