python-3.x - 使用python将XML解析为文本文件
问题描述
我在 XML 中有一个源部分,我试图以这种方式将值提取到文本文件中。
源1,ipset-1,IPSet,真
源 2,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))
解决方案
使用的解决方案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,true
推荐阅读
- r - R Shinyapp Highcharter - 如何添加多个注释
- pdfhtml - 使用 .print() 从 html 创建下载多页 pdf
- r - 无法在 ggplot2 中为同一功能组合颜色和形状图例
- excel - 对于 VBA Excel 中的每个循环
- mongodb - 无法启动 mongoDB 服务
- java - Spring没有找到符号@QueryResult
- python - Python pptx合并表行
- for-loop - 如何使脚本影响 Roblox LUA 中的所有子级?
- javascript - 我们如何使用 Puppeteer、黄瓜和 JS (npm) 实现浏览器的单例使用
- java - AWS API Gateway WebSocket 错误:意外响应:HTTP/1.1 101 切换协议