1

I have a source section in an XML from which I am trying to fetch the values in this way to a text file.

source1, ipset-1, IPSet, true

source2, ipset-2, IPSet, true

XML section:

<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>

Currently, my code gives me everything in one line.

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))

1 Answer 1

1

A solution using 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)

Creates source.txt:

source1,ipset-1,IPSet,true
source2,ipset-2,IPSet,true
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.