0

I'm trying to retrieve the value of a particular xml tag in an XML file. The problem is that it returns a memory address instead of the actual value.

Already tried multiple approaches using other libraries as well. Nothing really yielded the result.

from xml.etree import ElementTree
tree = ElementTree.parse('C:\\Users\\Sid\\Desktop\\Test.xml')
root = tree.getroot()
items = root.find("items")
item= items.find("item")
print(item)

Expected was 1 2 3 4. Actual : Memory address. XML File is :

<data>
    <items>
        <item>1</item>
    </items>
    <items>
        <item>2</item>
    </items>
    <items>
        <item>3</item>
    </items>
    <items>
        <item>4</item>
    </items>
</data>
2
  • 1
    Desired output is 1 2 3 4 Basically - All the numbers in the "Item" tag Commented Feb 18, 2019 at 6:33
  • see if the answer posted below helped? if it did, you may accept it by clicking on the tick sign beside it. cheers! Commented Feb 18, 2019 at 15:20

1 Answer 1

2

Using BeautifulSoup:

from bs4 import BeautifulSoup
import urllib

test = '''<data>
    <items>
        <item>1</item>
    </items>
    <items>
        <item>2</item>
    </items>
    <items>
        <item>3</item>
    </items>
    <items>
        <item>4</item>
    </items>
</data>'''

soup = BeautifulSoup(test, 'html.parser')
data = soup.find_all("item")

for d in data:
    print(d.text)

OUTPUT:

1
2
3
4

Using XML Element Tree:

from xml.etree import ElementTree
tree = ElementTree.parse('list.txt')
root = tree.getroot()

items = root.findall("items")

for elem in items:
    desired_tag = elem.find("item")
    print(desired_tag.text)

OUTPUT:

1                
2                
3                
4

EDIT:

If you want them printed in a line separated by spaces.

print(desired_tag.text, "\t", end = "")
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.