首页 > 解决方案 > 使用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))

标签: python-3.xparsingbeautifulsoupelementtree

解决方案


使用的解决方案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

推荐阅读