"lxmlasdict" allows you to treat lxml tree elements as if you were working with a dict
Project description
lxmlasdict
lxmlasdict
is just wrapper that allows you to treat lxml tree elements as if you were working with a dict. elements are searched only when accessing keys
pip install lxmlasdict
There are a few things to remember when working with this wrapper:
- the wrapper returns None only when accessing the keys "#text" and "@attr" if they do not exist, because they are final elements that have no children.
- the wrapper does not return None when accessing other keys that do not exist; instead, it returns an empty wrapper that can be checked for the None value or its length
Examples
>>> data = lxmlasdict.from_string("""
... <root a="testa">
... <child>
... <item>text 1</item>
... <item>text 2</item>
... </child>
... <example b="testb">
... example text
... </example>
... <test-ns:example xmlns:test-ns="http://test-ns.com/">
... example text (namespaced)
... </test-ns:example>
... </root>
... """)
Accessing to only one element
>>> print(data['child']['item']['#text'])
elements
Accessing to multiple elements
>>> for item in data['child']['item']:
... print(item['#text'])
...
elements
more elements
Checking for element presence
>>> if data['child']['item']:
... print('element exists')
... else:
... print('element does not exist')
...
element exists
>>> if data['child']['test']:
... print('element exists')
... else:
... print('element does not exist')
...
element does not exist
Counting the number of elements
>>> print(len(data['child']['item']))
2
Accessing attributes
>>> print(data['@a'])
testa
>>> print(data['example']['@b'])
testb
Accessing to elements with namespace
>>> print(data['test-ns:example']['#text'])
example text (namespaced)
Convert element and its contents to dict
>>> data = lxmlasdict.to_dict(data)
>>> print(json.dumps(data, indent=4))
{
"root": {
"child": {
"item": [
"text 1",
"text 2"
]
},
"example": {
"@b": "testb",
"#text": "example text"
},
"test-ns:example": "example text (namespaced)",
"@a": "testa"
}
}
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
lxmlasdict-0.1.0.tar.gz
(4.2 kB
view hashes)
Built Distribution
Close
Hashes for lxmlasdict-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 36c33852f2e4742d6cf3e4855e67165dac8ec63d993295a7b45c8337cbc73a1f |
|
MD5 | 86f44f781ce02d836ad1f78e69d0ed10 |
|
BLAKE2b-256 | 695925456c4ed9ee3a4f6e267dda5d0af38b9150d5e300817518247cfde77ef2 |