2016-08-09 7 views
3

Gibt es eine Bibliothek oder einen Mechanismus, mit denen ich die XML-Datei reduzieren kann?Wie glättet man XML-Dateien in Python?

Bestehende:

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

Wunsch:

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

Ich würde die ['xmltodict'] (https://github.com/martinblech/xmltodict) Bibliothek in Kombination mit [dies] (http://codereview.stackexchange.com/a/21035) antworten Sie, um ein "Diktat" zu verflachen. –

Antwort

1

von xmltodict mit Ihrer XML-Datei in ein Wörterbuch zu verwandeln, mit this answer in Kombination eine dict abzuflachen, sollte dies möglich sein.

Beispiel:

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

Ausgang:

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

Dies ist keine vollständige Implementierung, aber man konnte Vorteil lxmls's getpath nehmen:

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

Welche gibt Ihnen:

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 
Verwandte Themen