Skip to main content
 首页 » 编程设计

从 XML 中提取的 Python 保持相同的模式

2024年09月07日9kerrycode

我有一个具有以下架构的 XML:

<?xml version="1.0" encoding="utf-8" ?> 
<ROOT> 
<facturic id_user="18446195"><artfacturic/></facturic> 
<facturic id_user="18446195"><artfacturic/></facturic> 
<facturic id_user="34259554"><artfacturic/></facturic> 
</ROOT> 

它们的属性比 id_user 多得多,但只有那个是相关的,因为我需要将 xml 文件拆分为单独的文件,其中有重复的 id。

我设法使用下面的代码找到了重复项:

import os 
from xml.etree import ElementTree 
dom = ElementTree.parse(fullpath) 
findNode = 'facturic' 
findAttr = 'id_user' 
childNodes = dom.findall(findNode) 
userIdDict = dict()     #student={'name':'john','age':23} 
duplicateUserId = dict() 
 
#GET UNIQUE USER ID AND COUNT 
for c in childNodes: 
    userId = c.attrib.get(findAttr)  #gets attributes 
    #print(nrFact) 
 
    if userId not in userIdDict: 
        userIdDict[userId] = 1 
    else: 
        userIdDict[userId] = userIdDict[userId] + 1 
 
# print(userIdDict) 
for userId in userIdDict: 
    userIdCount = userIdDict[userId] 
    if userIdCount > 1: 
        duplicateUserId[userId]=userIdCount 

你们能告诉我如何创建仅包含重复节点但使用与初始文件相同的模式的新 xml 文件吗? 它应该类似于为每个重复节点创建新的 xml 文件,或者理想情况下,假设重复用户 ID 的最大数量为 4,只创建 4 个文件,但每个文件应仅包含具有所有其他初始属性的唯一 ID。

请您参考如下方法:

我会这样做:使用 defaultdict(list)根据单个 id_user 值收集节点。然后,对生成的字典进行后处理,将副本写入单独的文件。使用 lxml.etree:

from collections import defaultdict 
from lxml import etree 
 
tree = etree.parse("input.xml") 
 
facturics = defaultdict(list) 
 
for node in tree.xpath(".//facturic"): 
    facturics[node.attrib["id_user"]].append(node) 
 
for user_id, nodes in facturics.items(): 
    if len(nodes) > 1:  # save duplicates 
        with open("{user_id}.xml".format(user_id=user_id), "w") as output_file: 
            root = etree.Element("ROOT") 
            for node in nodes: 
                root.append(node) 
            etree.ElementTree(root).write(output_file, pretty_print=True) 

运行这段代码后,会在当前目录下生成一个名为18446195.xml的新文件,内容如下:

<ROOT> 
    <facturic id_user="18446195"><artfacturic/></facturic> 
    <facturic id_user="18446195"><artfacturic/></facturic> 
</ROOT>