Last active
August 29, 2015 14:26
-
-
Save caiwan/80ded620f978924f631e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import xml.etree.ElementTree as ET | |
class XMLBuilder(object): | |
def __init__(self, _outfile): | |
self._outfile = _outfile | |
self._outXML = None | |
def __enter__(self): | |
return self | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
assert isinstance(self._outXML, ET.ElementTree) | |
self._outXML.write(self._outfile, encoding="UTF-8", xml_declaration=True, method="xml") | |
def pushXML(self, content): | |
if len(content) == 0: | |
return | |
tree = ET.fromstringlist(content) | |
if self._outXML is None: | |
self._outXML = ET.ElementTree(tree) | |
return | |
else: | |
for child in tree: | |
self._outXML.getroot().append(child) | |
if __name__ == "__main__": | |
infile = sys.stdin | |
# infile = open('input.xml', 'r') | |
outfile = "result.xml" | |
if len(sys.argv) == 2: | |
outfile = sys.argv[1] | |
builder = XMLBuilder(outfile) | |
XMLstring = [] | |
with builder: | |
with infile: | |
for line in infile: | |
if ("<?xml" in line): | |
builder.pushXML(XMLstring) | |
XMLstring = [] | |
XMLstring.append(line) | |
builder.pushXML(XMLstring) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment