hat.json.vt
Virtual tree XML parser
1"""Virtual tree XML parser""" 2 3import os 4import xml.sax 5import xml.sax.handler 6import xml.sax.xmlreader 7 8from hat.json.data import Data 9 10 11def parse(file: os.PathLike | xml.sax.xmlreader.InputSource 12 ) -> Data: 13 r"""Parse XML document into virtual tree 14 15 Each element is recursively parsed into a list with the following 16 structure, starting from the root of a document: 17 18 * First item is a valid CSS selector string, consisting of element tag 19 name; and optionally `id` and `class` attributes if present. 20 21 * If the element has attributes other than `id` or `class`, they are 22 stored as a second item. The item is a dictionary which has an 23 `attrs` key, whose value is another dictionary, with key-value pairs 24 representing attribute names and their values, respectively. 25 26 * All other items are element content. Each item is either a 27 recursively parsed element child (a list), or text (a string). 28 Consecutive text items are equivalent to their concatenation. 29 30 Resulting structure is JSON serializable. 31 32 Namespace prefix declaration attributes (`xmlns:*`) and prefixed elements 33 are ignored. 34 35 Example usage:: 36 37 import io 38 from hat import json 39 40 xml = '''\ 41 <html> 42 <body> 43 <div id="first" class="c1 c2"> 44 Banana 45 </div> 46 Orange 47 <br/> 48 <span id="second" style="color:green"> 49 Watermelon 50 </span> 51 </body> 52 </html> 53 ''' 54 stripped = ''.join(line.lstrip() for line in xml.split('\n')) 55 stream = io.StringIO(stripped) 56 parsed = json.vt.parse(stream) 57 58 Output:: 59 60 ['html', 61 ['body', 62 ['div#first.c1.c2', 63 "Banana" 64 ], 65 "Orange", 66 ['br'], 67 ['span#second', 68 {'attrs': 69 {'style': "color:green"} 70 }, 71 "Watermelon" 72 ] 73 ] 74 ] 75 76 """ 77 handler = _ContentHandler() 78 parser = xml.sax.make_parser() 79 parser.setContentHandler(handler) 80 parser.setFeature(xml.sax.handler.feature_external_ges, False) 81 parser.setFeature(xml.sax.handler.feature_external_pes, False) 82 parser.parse(file) 83 return handler.root 84 85 86class _ContentHandler(xml.sax.ContentHandler): 87 88 def __init__(self): 89 self._root = None 90 self._stack = [] 91 self._skip_depth = 0 92 93 @property 94 def root(self): 95 return self._root 96 97 def startElement(self, name, attrs): 98 if ':' in name or self._skip_depth: 99 self._skip_depth += 1 100 return 101 102 attrs = {k.split(':')[-1]: v 103 for k, v in attrs.items() 104 if not k.startswith('xmlns:')} 105 106 elm_id = attrs.pop('id', '') 107 elm_class = '.'.join(i for i in attrs.pop('class', '').split(' ') if i) 108 element = [name + 109 (f'#{elm_id}' if elm_id else '') + 110 (f'.{elm_class}' if elm_class else '')] 111 112 if attrs: 113 element.append({'attrs': attrs}) 114 115 if self._stack: 116 self._stack[-1].append(element) 117 118 else: 119 self._root = element 120 121 self._stack.append(element) 122 123 def endElement(self, name): 124 if self._skip_depth: 125 self._skip_depth -= 1 126 return 127 128 self._stack.pop() 129 130 def characters(self, content): 131 if self._skip_depth: 132 return 133 134 self._stack[-1].append(content)
def
parse( file: os.PathLike | xml.sax.xmlreader.InputSource) -> None | bool | int | float | str | List[None | bool | int | float | str | List[ForwardRef('Data')] | Dict[str, ForwardRef('Data')]] | Dict[str, None | bool | int | float | str | List[ForwardRef('Data')] | Dict[str, ForwardRef('Data')]]:
12def parse(file: os.PathLike | xml.sax.xmlreader.InputSource 13 ) -> Data: 14 r"""Parse XML document into virtual tree 15 16 Each element is recursively parsed into a list with the following 17 structure, starting from the root of a document: 18 19 * First item is a valid CSS selector string, consisting of element tag 20 name; and optionally `id` and `class` attributes if present. 21 22 * If the element has attributes other than `id` or `class`, they are 23 stored as a second item. The item is a dictionary which has an 24 `attrs` key, whose value is another dictionary, with key-value pairs 25 representing attribute names and their values, respectively. 26 27 * All other items are element content. Each item is either a 28 recursively parsed element child (a list), or text (a string). 29 Consecutive text items are equivalent to their concatenation. 30 31 Resulting structure is JSON serializable. 32 33 Namespace prefix declaration attributes (`xmlns:*`) and prefixed elements 34 are ignored. 35 36 Example usage:: 37 38 import io 39 from hat import json 40 41 xml = '''\ 42 <html> 43 <body> 44 <div id="first" class="c1 c2"> 45 Banana 46 </div> 47 Orange 48 <br/> 49 <span id="second" style="color:green"> 50 Watermelon 51 </span> 52 </body> 53 </html> 54 ''' 55 stripped = ''.join(line.lstrip() for line in xml.split('\n')) 56 stream = io.StringIO(stripped) 57 parsed = json.vt.parse(stream) 58 59 Output:: 60 61 ['html', 62 ['body', 63 ['div#first.c1.c2', 64 "Banana" 65 ], 66 "Orange", 67 ['br'], 68 ['span#second', 69 {'attrs': 70 {'style': "color:green"} 71 }, 72 "Watermelon" 73 ] 74 ] 75 ] 76 77 """ 78 handler = _ContentHandler() 79 parser = xml.sax.make_parser() 80 parser.setContentHandler(handler) 81 parser.setFeature(xml.sax.handler.feature_external_ges, False) 82 parser.setFeature(xml.sax.handler.feature_external_pes, False) 83 parser.parse(file) 84 return handler.root
Parse XML document into virtual tree
Each element is recursively parsed into a list with the following structure, starting from the root of a document:
* First item is a valid CSS selector string, consisting of element tag
name; and optionally `id` and `class` attributes if present.
* If the element has attributes other than `id` or `class`, they are
stored as a second item. The item is a dictionary which has an
`attrs` key, whose value is another dictionary, with key-value pairs
representing attribute names and their values, respectively.
* All other items are element content. Each item is either a
recursively parsed element child (a list), or text (a string).
Consecutive text items are equivalent to their concatenation.
Resulting structure is JSON serializable.
Namespace prefix declaration attributes (xmlns:*) and prefixed elements
are ignored.
Example usage::
import io
from hat import json
xml = '''\
Banana
Orange
Watermelon
'''
stripped = ''.join(line.lstrip() for line in xml.split('\n'))
stream = io.StringIO(stripped)
parsed = json.vt.parse(stream)
Output::
['html',
['body',
['div#first.c1.c2',
"Banana"
],
"Orange",
['br'],
['span#second',
{'attrs':
{'style': "color:green"}
},
"Watermelon"
]
]
]