Skip to content

Commit

Permalink
fix #15915
Browse files Browse the repository at this point in the history
  • Loading branch information
namdre committed Dec 16, 2024
1 parent df0acfb commit 2efb4de
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions tools/xml/xml2csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def depth(self):

class AttrFinder(NestingHandler):

def __init__(self, xsdFile, source, split):
def __init__(self, xsdFile, source, split, keepAttrs=None):
NestingHandler.__init__(self)
self.tagDepths = {} # tag -> depth of appearance
self.tagAttrs = collections.defaultdict(
Expand All @@ -71,6 +71,7 @@ def __init__(self, xsdFile, source, split):
self.attrs = {}
self.depthTags = {} # child of root: depth of appearance -> tag list
self.rootDepth = 1 if split else 0
self.keepAttrs = keepAttrs
if xsdFile:
self.xsdStruc = xsd.XsdStructure(xsdFile)
if split:
Expand Down Expand Up @@ -128,6 +129,8 @@ def startElement(self, name, attrs):
return
# collect attributes
for a in sorted(list(attrs.keys())):
if self.keepAttrs is not None and not a in self.keepAttrs:
continue
if a not in self.tagAttrs[name] and ":" not in a:
self.tagAttrs[name][a] = xsd.XmlAttribute(a)
if not (name, a) in self.renamedAttrs:
Expand Down Expand Up @@ -245,6 +248,8 @@ def get_options(arglist=None):
help="xsd schema to use")
optParser.add_argument("-a", "--validation", action="store_true", default=False,
help="enable schema validation")
optParser.add_argument("--keep-attributes", dest="keepAttrs",
help="Only keep the given attributes")
optParser.add_argument("-p", "--split", action="store_true", default=False,
help="split in different files for the first hierarchy level")
options = optParser.parse_args(arglist)
Expand All @@ -261,13 +266,15 @@ def get_options(arglist=None):
if options.output and options.output.isdigit() and options.split:
print("it is not possible to use splitting together with stream output", file=sys.stderr)
sys.exit()
if options.keepAttrs:
options.keepAttrs = set(options.keepAttrs.split(','))
return options


def main(args=None):
options = get_options(args)
# get attributes
attrFinder = AttrFinder(options.xsd, options.source, options.split)
attrFinder = AttrFinder(options.xsd, options.source, options.split, options.keepAttrs)
# write csv
handler = CSVWriter(attrFinder, options)
if options.validation:
Expand Down

0 comments on commit 2efb4de

Please sign in to comment.