Hướng dẫn python flatten xml - python làm phẳng xml

Có thư viện hoặc cơ chế tôi có thể sử dụng để làm phẳng tệp XML không?

Existing:


    
        a
        00:00:00
        00:00:00
        N

Desired:

A.B.ConnectionType = a
A.B.StartTime = 00:00:00
A.B.EndTime = 00:00:00
A.B.UseDataDictionary = N

Khi được hỏi ngày 9 tháng 8 năm 2016 lúc 13:56Aug 9, 2016 at 13:56

Hướng dẫn python flatten xml - python làm phẳng xml

James Raitsevjames RaitsevJames Raitsev

89,7K150 huy hiệu vàng328 Huy hiệu bạc467 Huy hiệu đồng150 gold badges328 silver badges467 bronze badges

1

Bằng cách sử dụng xmltodict để chuyển đổi tệp XML của bạn thành từ điển, kết hợp với câu trả lời này để làm phẳng dict, điều này có thể có được.

Example:

# Original code: https://codereview.stackexchange.com/a/21035
from collections import OrderedDict

def flatten_dict(d):
    def items():
        for key, value in d.items():
            if isinstance(value, dict):
                for subkey, subvalue in flatten_dict(value).items():
                    yield key + "." + subkey, subvalue
            else:
                yield key, value

    return OrderedDict(items())

import xmltodict

# Convert to dict
with open('test.xml', 'rb') as f:
    xml_content = xmltodict.parse(f)

# Flatten dict
flattened_xml = flatten_dict(xml_content)

# Print in desired format
for k,v in flattened_xml.items():
    print('{} = {}'.format(k,v))

Output:

A.B.ConnectionType = a
A.B.StartTime = 00:00:00
A.B.EndTime = 00:00:00
A.B.UseDataDictionary = N

Đã trả lời ngày 9 tháng 8 năm 2016 lúc 14:22Aug 9, 2016 at 14:22

Hướng dẫn python flatten xml - python làm phẳng xml

1

Đây không phải là một triển khai hoàn chỉnh nhưng bạn có thể tận dụng lợi thế của LXMLS:

xml = """
            
               a
               00:00:00
               00:00:00
               N
               G
               
            
       """


from lxml import etree
from io import StringIO
tree = etree.parse(StringIO(xml))

root = tree.getroot().tag
for node in tree.iter():
    for child in node.getchildren():
         if child and child.text.strip():
            print("{}.{} = {}".format(root, ".".join(tree.getelementpath(child).split("/")), child.text.strip()))

Mà cung cấp cho bạn:

A.B.ConnectionType = a
A.B.StartTime = 00:00:00
A.B.EndTime = 00:00:00
A.B.UseDataDictionary = N
A.B.UseDataDictionary.UseDataDictionary2 = G

đóng hộp

3,4782 Huy hiệu vàng24 Huy hiệu bạc26 Huy hiệu đồng2 gold badges24 silver badges26 bronze badges

Đã trả lời ngày 13 tháng 8 năm 2016 lúc 23:55Aug 13, 2016 at 23:55

Hướng dẫn python flatten xml - python làm phẳng xml

1

Dưới đây là phiên bản cải tiến từ ƙɍỉSƭơƒ cũng xử lý danh sách lồng nhau:

def flatten_dict(d):
    def items():
        for key, value in d.items():
            # nested subtree
            if isinstance(value, dict):
                for subkey, subvalue in flatten_dict(value).items():
                    yield '{}.{}'.format(key, subkey), subvalue
            # nested list
            elif isinstance(value, list):
                for num, elem in enumerate(value):
                    for subkey, subvalue in flatten_dict(elem).items():
                        yield '{}.[{}].{}'.format(key, num, subkey), subvalue
            # everything else (only leafs should remain)
            else:
                yield key, value

Đã trả lời ngày 28 tháng 5 năm 2021 lúc 19:46May 28, 2021 at 19:46

1