简体   繁体   中英

Python XML Element Tree finding the value of an XML tag

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM