-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter13-parse XML
54 lines (50 loc) · 1.47 KB
/
chapter13-parse XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Wire Format: The two types of serialization formats that we're going to talk about are XML and JSON
Node; Schema;Parsing
import xml.etree.ElementTree as ET
data = '''
<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes"/>
</person>'''
tree = ET.fromstring(data)
print('Name:', tree.find('name').text)
print('Attr:', tree.find('email').get('hide'))
import xml.etree.ElementTree as ET
input = '''
<stuff>
<users>
<user x="2">
<id>001</id>
<name>Chuck</name>
</user>
<user x="7">
<id>009</id>
<name>Brent</name>
</user>
</users>
</stuff>'''
stuff = ET.fromstring(input)
lst = stuff.findall('users/user')
print('User count:', len(lst))
for item in lst:
print('Name', item.find('name').text)
print('Id', item.find('id').text)
print('Attribute', item.get("x"))
----------------------------------
PS C:\Users\Sharon\code\test> set-location C:\Users\Sharon\code , cd
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
url = 'http://py4e-data.dr-chuck.net/comments_103948.xml'
data = urllib.request.urlopen(url).read()
tree = ET.fromstring(data)
lst= tree.findall('.//comment') # lst= tree.findall('comments/comment') # print('Comment count:', len(lst))
count=[int(item.find('count').text) for item in lst]
def sum_list(nums):
sum=0
for num in nums:
sum=sum+num
return sum
print (sum_list(count))