Python 3.3: Convert XML to YAML



I'm trying to convert XML files to YAML using Python 3.3. This is my code:



#! /etc/python3

test_filename_input = './reference-conversions/wikipedia-example.xml'
test_filename_output = 'wikipedia-example_xml_read-as-binary.yaml'

file_object = open( test_filename_input, 'rb')
data_in = file_object.read()
file_object.close()

from xml.dom.minidom import parseString
document_object = parseString( data_in)

import yaml
stream = open( test_filename_output, 'w')
yaml.dump( document_object, stream)
stream.close()


As a reference I used the XML-file from here:



<person>
<firstName>John</firstName>
<lastName>Smith</lastName>
<age>25</age>
<address>
<streetAddress>21 2nd Street</streetAddress>
<city>New York</city>
<state>NY</state>
<postalCode>10021</postalCode>
</address>
<phoneNumbers>
<phoneNumber type="home">212 555-1234</phoneNumber>
<phoneNumber type="fax">646 555-4567</phoneNumber>
</phoneNumbers>
<gender>
<type>male</type>
</gender>
</person>


which should result in something like this:



---
firstName: John
lastName: Smith
age: 25
address:
streetAddress: 21 2nd Street
city: New York
state: NY
postalCode: 10021

phoneNumber:
-
type: home
number: 212 555-1234
-
type: fax
number: 646 555-4567
gender:
type: male


However, the result is:



&id001 !!python/object/new:xml.dom.minidom.Document
state: !!python/tuple
- implementation: !!python/object:xml.dom.minidom.DOMImplementation {}
- _elem_info: {}
_id_cache: {}
_id_search_stack: null
childNodes: !!python/object/new:xml.dom.minicompat.NodeList
listitems:
- &id039 !!python/object/new:xml.dom.minidom.Element
state: !!python/tuple
- null
- _attrs: null
_attrsNS: null
childNodes: !!python/object/new:xml.dom.minicompat.NodeList
listitems:
- &id045 !!python/object/new:xml.dom.minidom.Text
state: !!python/tuple
- null
- _data: "\n "
nextSibling: &id002 !!python/object/new:xml.dom.minidom.Element
state: !!python/tuple
- null
- _attrs: null
_attrsNS: null
childNodes: !!python/object/new:xml.dom.minicompat.NodeList
listitems:
[...]


Any idea, how to get PyYAML filter out the object-stuff from xml.dom.minidom or any alternative to using xml.dom.minidom?


Thanks!


No comments:

Post a Comment