我在XML中有一个source部分,我试图以这种方式将值提取到一个文本文件中。
source1,ipset-1,IPSet,真
source2,ipset-2,IPSet,真
XML部分:
<sources excluded="false">
<source>
<name>source1</name>
<value>ipset-1</value>
<type>IPSet</type>
<isValid>true</isValid>
</source>
<source>
<name>source2</name>
<value>ipset-2</value>
<type>IPSet</type>
<isValid>true</isValid>
</source>
</sources>目前,我的代码在一行中提供了所有内容。
import xml.etree.ElementTree as ET
tree = ET.fromstring(xml_file)
for node in tree.iter('source'):
print('\n')
with open("source.txt", "a") as file:
for elem in node.iter():
if not elem.tag==node.tag:
file.write("{},".format(elem.text))
print("{}: {}".format(elem.tag, elem.text))发布于 2021-06-01 18:28:50
使用beautifulsoup的解决方案
from bs4 import BeautifulSoup
xml_doc = """
<sources excluded="false">
<source>
<name>source1</name>
<value>ipset-1</value>
<type>IPSet</type>
<isValid>true</isValid>
</source>
<source>
<name>source2</name>
<value>ipset-2</value>
<type>IPSet</type>
<isValid>true</isValid>
</source>
</sources>
"""
soup = BeautifulSoup(xml_doc, "lxml")
with open("source.txt", "w") as f_out:
for tag in soup.select("source"):
print(",".join(t.text for t in tag.select("*")), file=f_out)创建source.txt
source1,ipset-1,IPSet,true
source2,ipset-2,IPSet,truehttps://stackoverflow.com/questions/67786921
复制相似问题