简体   繁体   中英

Read data from XML using python

I have data received from web like this:

<collective2>
    <status>OK</status>
        <positionstatus>
        <calctime>2017-10-17 03:25:57:000</calctime>
        <symbol>AA</symbol>
        <position>102</position>
        <averagecost>48.86</averagecost>
    </positionstatus>
</collective2>

Any Help how to read it. for example get 'OK' ,... Also 'AA' Thanks in advance.

I have tried:

import xml.etree.ElementTree as ET
data1 = ET.fromstring(data)
ok = data1.get('status') 

You're not giving a lot of information on what you need exactly, but simply reading the first few paragraphs of the xml.etree documentation should have told you that the following code provides you with the results you are asking for:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import xml.etree.ElementTree as ET

tree = ET.parse('data.xml')

print(tree.find('status').text)                         # OK
print(tree.find('positionstatus').find('symbol').text)  # AA

Hope this helps.

This is my method:

>>> from lxml import html as HTML
>>> data1 = HTML.fromstring(data)
print data1.xpath('//status')[0].text
OK
>>> print data1.xpath('//symbol')[0].text
AA

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