gpt4 book ai didi

python - 读取 xml 并尝试将其提取到 2 个不同的 xml 中

转载 作者:太空宇宙 更新时间:2023-11-03 14:42:28 25 4
gpt4 key购买 nike

我有一个如下所示的 xml 文件:

 <?xml version="1.0" encoding="ASCII" standalone="yes"?>
<file>
<records>
<record>
<device_serial_number>PAD203137687</device_serial_number>
<device_serial_number_2>203137687</device_serial_number_2>
</record>
<record>
<device_serial_number>PAD203146024</device_serial_number>
<device_serial_number_2>203146024</device_serial_number_2>
</record>
</records>
</file>

现在我想检查每条记录中的device_serial_number,并检查最后4个字符是否为6024,如果是,则将完整的记录数据写入名为one.xml的newxml文件

我已经尝试过以下方法

  from xml.etree import ElementTree as ET
tree = ET.parse('C:\\Users\\x3.xml')
for node in tree.findall('.//records//record/'):
print("<"+str(node.tag) + "> "+"<"+str(node.text)+"/>")

最佳答案

因此,根据我的理解,您可以尝试如下所示:

     from xml.etree import ElementTree as ET
from xml.dom.minidom import getDOMImplementation
from xml.dom.minidom import parseString
tree = ET.parse('C:\\Users\\x3.xml')
root = tree.getroot()
impl = getDOMImplementation()
#print(root) #just to check
commands = root.findall(".//records//")
recs=[c for c in commands if c.find('device_serial_number')!=None and
c.find('soc_id').text[-4:]=='6024']
bb=""
for rec in recs:
aa=(parseString(ET.tostring(rec)).toprettyxml(''))
bb=bb+aa
#print(bb) #it will have all data you need, write these into files
newdoc = impl.createDocument(None, bb, None)
newdoc.writexml(open('your_output_file.xml', 'w'),
indent="",
addindent="",
newl='') #check documentation for these

这是link有关写入 xml 文件的文档。

Node.writexml(writer, indent=”“, addindent=””, newl=””)将 XML 写入 writer 对象。编写器应该有一个与文件对象接口(interface)相匹配的 write() 方法。 indent参数是当前节点的缩进。 addindent 参数是用于当前节点的子节点的增量缩进。 newl 参数指定用于终止换行符的字符串。

以上内容来自xml.dom.minidom文档。里面解释了如何编写以及它们的含义。

最后,这将帮助您将所需的数据以 xml 格式写入 writexml 中指定的文件。

关于python - 读取 xml 并尝试将其提取到 2 个不同的 xml 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46475724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com