Skip to content

Instantly share code, notes, and snippets.

@strangeman
Created February 17, 2017 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save strangeman/a2c9ffa9f69390f0361680f7ee255ec4 to your computer and use it in GitHub Desktop.
Save strangeman/a2c9ffa9f69390f0361680f7ee255ec4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys, string, re, types
import yaml
from xml.dom import minidom
from xml.dom import Node
#
# Convert an XML document (file) to YAML and write it to stdout.
#
def convertXml2Yaml(inFileName):
doc = minidom.parse(inFileName)
out = []
out.append('---\n')
level = 0
root = doc.childNodes[0]
convertXml2YamlAux(root, level, out)
content = "".join(out)
sys.stdout.write(content)
def convertXml2YamlAux(obj, level, out):
level += 1
# Dump the attributes.
attrs = obj.attributes
if attrs.length > 0:
level += 1
for idx in range(attrs.length):
attr = attrs.item(idx)
out.append(' %s: %s\n' % (attr.name, attr.value))
level -= 1
# Dump the text.
text = []
for child in obj.childNodes:
if child.nodeType == Node.TEXT_NODE and \
not isAllWhiteSpace(child.nodeValue):
text.append(child.nodeValue)
if text:
textStr = "".join(text)
out.append(' value: "%s"\n' % textStr)
# Dump the children.
found = 0
for child in obj.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
found = 1
break
if found:
level += 1
for child in obj.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
convertXml2YamlAux(child, level, out)
NonWhiteSpacePattern = re.compile('\S')
def isAllWhiteSpace(text):
if NonWhiteSpacePattern.search(text):
return 0
return 1
USAGE_TEXT = """
Convert a file from YAML to XML or XML to YAML and write it to stdout.
Usage: python convertyaml.py <option> <in_file>
Options:
-x2y Convert XML document to YAML.
"""
def usage():
print USAGE_TEXT
sys.exit(-1)
def main():
args = sys.argv[1:]
if len(args) != 2:
usage()
option = args[0]
inFileName = args[1]
if option == '-x2y':
convertXml2Yaml(inFileName)
else:
usage()
if __name__ == '__main__':
main()
#import pdb
#pdb.run('main()')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment