2016-08-09 102 views
3

是否有可用於壓扁XML文件的庫或機制?如何在Python中壓扁XML文件

現有:

<A> 
    <B> 
     <ConnectionType>a</ConnectionType> 
     <StartTime>00:00:00</StartTime> 
     <EndTime>00:00:00</EndTime> 
     <UseDataDictionary>N</UseDataDictionary> 

期望:

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

我會看看['xmltodict'](https://github.com/martinblech/xmltodict)庫與[this](http://codereview.stackexchange.com/a/21035) )回答扁平化'dict'。 –

回答

1

通過使用xmltodict到您的XML文件this answer轉換成一個字典,結合扁平化一個dict,這應該是可能的。

例子:

# 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)) 

輸出:

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

這是不是一個完整的實現,但你可以採取的lxmls's getpath優勢:

xml = """<A> 
      <B> 
       <ConnectionType>a</ConnectionType> 
       <StartTime>00:00:00</StartTime> 
       <EndTime>00:00:00</EndTime> 
       <UseDataDictionary>N 
       <UseDataDictionary2>G</UseDataDictionary2> 
       </UseDataDictionary> 
      </B> 
     </A>""" 


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

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

它給你:

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