首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python将XML解析为文本文件

使用python将XML解析为文本文件
EN

Stack Overflow用户
提问于 2021-06-01 18:11:51
回答 1查看 25关注 0票数 1

我在XML中有一个source部分,我试图以这种方式将值提取到一个文本文件中。

source1,ipset-1,IPSet,真

source2,ipset-2,IPSet,真

XML部分:

代码语言:javascript
复制
<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>

目前,我的代码在一行中提供了所有内容。

代码语言:javascript
复制
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))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-01 18:28:50

使用beautifulsoup的解决方案

代码语言:javascript
复制
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

代码语言:javascript
复制
source1,ipset-1,IPSet,true
source2,ipset-2,IPSet,true
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67786921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档