Skip to main content
 首页 » 编程设计

python之XML 文件生成不需要的数据

2025年02月15日8三少

从不同的 xml 文件读取后,我尝试向 xml 文件写入一些内容,一切正常,但我生成的 xml 文件中几乎没有不需要的标签作为输出。

这是我尝试过的

    from xml.etree import ElementTree as ET 
    from xml.dom.minidom import getDOMImplementation 
    from xml.dom.minidom import parseString 
    tree = ET.parse('C:\\Users\\ca33.xml') 
    root = tree.getroot() 
    impl = getDOMImplementation() 
    #print(root) 
    header = [root.find('header')] 
    for h in header: 
        h1=(parseString(ET.tostring(h)).toprettyxml('')) 
        #print(h1) 
    commands = root.findall(".//records//") 
    recs=[c for c in commands if c.find('soc_id')!=None and   c.find('soc_id').text[:9]=='000001051'] 
    bb="" 
    for rec in recs: 
        aa=(parseString(ET.tostring(rec)).toprettyxml('')) 
        bb=bb+aa 
    #print(bb) 
    newdoc = impl.createDocument(None, "file"+h1+bb, None) 
    newdoc.writexml(open('data.xml', 'w'),'\n'.join([line for line in newdoc.toprettyxml(indent=' '*2).split('\n') if line.strip()])) 

我将输出 data.xml 文件作为。

<?xml version="1.0" ?><?xml version="1.0" ?> 
<file<?xml version="1.0" ?> 
<header> 
<number_of_records>41</number_of_records> 
</header> 
<?xml version="1.0" ?> 
<record> 
<soc_id>00000105139E3B82</soc_id> 
</record> 
<?xml version="1.0" ?> 
<soc_id>00000105139E3640</soc_id> 
</record> 
<?xml version="1.0" ?> 
<header> 
 
 
<number_of_records>41</number_of_records> 

所以你可以看到很多<?xml version="1.0" ?>的标签到处都在生成,最后它再次从第一个开始写入数据,但留下 2 行间距

请您参考如下方法:

因此,我的理解是您首先尝试读取一个 xml 文件,然后您尝试将相同的数据写入到不同的文件中。 在这个过程中你遇到了问题

   from xml.etree import ElementTree as ET 
   tree = ET.parse('C:\\Users\\ca33.xml') 
   root = tree.getroot() 
   for header_ex in root.findall('header'): 
       h = [ET.tostring(c) for c in header_ex] 
       str_header=str(h) 
   for record_ex in root.findall('records'): 
       r = [ET.tostring(c) for c in record if c.find('soc_id')!=None and c.find('soc_id').text[:9]=='000001051'] 
       for rec in r: 
           str_rec=str(rec) 
   with open("output.xml","w") as f: 
       f.write("<?xml version='1.0' encoding='ASCII' standalone='yes'?>") 
       f.write("<file>"+"<header>"+str_header+"</header>") 
       f.close() 

因为你没有发布任何随机数据,我假设它是你发布问题的方式。我假设记录是一个标签并且它里面有更多或更多的子/子标签,这就是原因我在上面循环两次。

And also stop using unnecessary imports in your code.