sửa đổi của tôi về câu trả lời của Daniel, để đưa ra một marginall y gọn gàng từ điển:
def xml_to_dictionary(element):
l = len(namespace)
dictionary={}
tag = element.tag[l:]
if element.text:
if (element.text == ' '):
dictionary[tag] = {}
else:
dictionary[tag] = element.text
children = element.getchildren()
if children:
subdictionary = {}
for child in children:
for k,v in xml_to_dictionary(child).items():
if k in subdictionary:
if (isinstance(subdictionary[k], list)):
subdictionary[k].append(v)
else:
subdictionary[k] = [subdictionary[k], v]
else:
subdictionary[k] = v
if (dictionary[tag] == {}):
dictionary[tag] = subdictionary
else:
dictionary[tag] = [dictionary[tag], subdictionary]
if element.attrib:
attribs = {}
for k,v in element.attrib.items():
attribs[k] = v
if (dictionary[tag] == {}):
dictionary[tag] = attribs
else:
dictionary[tag] = [dictionary[tag], attribs]
return dictionary
namespace là chuỗi xmlns, bao gồm niềng răng, rằng ElementTree prepends để tất cả các thẻ, vì vậy ở đây tôi đã xóa nó như có một không gian tên cho toàn bộ tài liệu
NB mà tôi điều chỉnh xml thô quá, do đó 'rỗng' thẻ sẽ tạo ra tối đa là một '' tài sản văn bản trong các đại diện ElementTree
spacepattern = re.compile(r'\s+')
mydictionary = xml_to_dictionary(ElementTree.XML(spacepattern.sub(' ', content)))
sẽ cung cấp cho ví dụ
{'note': {'to': 'Tove',
'from': 'Jani',
'heading': 'Reminder',
'body': "Don't forget me this weekend!"}}
nó được thiết kế cho xml cụ thể mà về cơ bản là tương đương với json, nên xử lý yếu tố thuộc tính như
<elementName attributeName='attributeContent'>elementContent</elementName>
quá
có khả năng sáp nhập các từ điển thuộc tính/thẻ phụ điển tương tự như thẻ phụ như thế nào lặp lại được hợp nhất, mặc dù lồng các danh sách có vẻ thích hợp :-)
BeautifulSoup chuyển đổi mọi thứ thành thấp hơn. Điều đó thật sự rất tệ. Tôi phải bảo tồn các trường hợp thẻ và giá trị! – user236215
Tác giả của BeautifulSoup nói rằng điều này thực hiện điều này bởi vì HTMLParser làm điều đó. "Nếu bạn cần bảo quản thẻ, hãy thử lxml". – nealmcb