栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

合并带有嵌套元素的xml文件,而无需外部库

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

合并带有嵌套元素的xml文件,而无需外部库

您发布的代码正在执行的操作是组合所有元素,而不管是否存在具有相同标签的元素。因此,您需要遍历元素并按照您认为合适的方式手动检查和组合它们,因为这不是处理XML文件的标准方法。我无法比代码更好地解释它,所以在这里或多或少地注释了一下:

from xml.etree import ElementTree as etclass XMLCombiner(object):    def __init__(self, filenames):        assert len(filenames) > 0, 'No filenames!'        # save all the roots, in order, to be processed later        self.roots = [et.parse(f).getroot() for f in filenames]    def combine(self):        for r in self.roots[1:]: # combine each element with the first one, and update that self.combine_element(self.roots[0], r)        # return the string representation        return et.tostring(self.roots[0])    def combine_element(self, one, other):        """        This function recursively updates either the text or the children        of an element if another element is found in `one`, or adds it        from `other` if not found.        """        # Create a mapping from tag name to element, as that's what we are fltering with        mapping = {el.tag: el for el in one}        for el in other: if len(el) == 0:     # Not nested     try:         # Update the text         mapping[el.tag].text = el.text     except KeyError:         # An element with this name is not in the mapping         mapping[el.tag] = el         # Add it         one.append(el) else:     try:         # Recursively process the element, and update it in the same way         self.combine_element(mapping[el.tag], el)     except KeyError:         # Not in the mapping         mapping[el.tag] = el         # Just add it         one.append(el)if __name__ == '__main__':    r = XMLCombiner(('sample1.xml', 'sample2.xml')).combine()    print '-'*20    print r


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/641092.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号