@franciscoareasareas/

search_in_python27

Python 2.7

Tutorial to search in python 2.7

fork
loading
Files
  • main.py
main.py
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
xml = '''
<Catalog>
    <Books>
        <Book id="1" price="7.95">
            <Title>Do Androids Dream of Electric Sheep?</Title>
            <Author>Philip K. Dick</Author>
        </Book>
        <Book id="5" price="5.95">
            <Title>The Colour of Magic</Title>
            <Author>Terry Pratchett</Author>
        </Book>
        <Book id="7" price="6.95">
            <Title>The Eye of The World</Title>
            <Author>Robert Jordan</Author>
        </Book>
    </Books>
</Catalog>
'''

import xml.etree.cElementTree as ET
tree = ET.XML(xml)
print 'All books'
books = tree.findall('Books/Book')
for book in books:
  print ET.tostring(book, method='xml')

print 'book called "Colour of Magic"'
book = tree.find("Books/Book[Title='The Colour of Magic']") 
print ET.tostring(book, method='xml')

print 'book with id 5'
book = tree.find("Books/Book[@id='5']")
print ET.tostring(book, method='xml')

print 'second book'
book = tree.find("Books/Book[2]")
print ET.tostring(book, method='xml')

print 'last book'
book = tree.find("Books/Book[last()]")
print ET.tostring(book, method='xml')

print 'All authors'
authors = tree.findall(".//Author")
for author in authors:
  print ET.tostring(author, method='xml')