Author Topic: التعامل مع ال XML من خلال etree  (Read 588 times)

Ahmed Youssef

  • Helping Freak
  • Administrator
  • Active Member
  • *****
  • Posts: 242
    • View Profile
    • WWW
    • Email
التعامل مع ال XML من خلال etree
« on: September 11, 2009, 11:07:26 AM »

An Element on a Tree


فى موضوعنا عندنا عنصرين
Element وهو حاوية مرنة مصممة لتخزين هياكل البيانات بصورة هيكلية فى الميمورى وهو بين الlist وال dict –هنعرف ليه

ليه بعض الصفات المميزة ليه زى tag وهو string بيعبر عما يمثله العنصر –نوعه من الآخر
مجموعة من attributes مخزنة فى dict بإسم attrib
text وهو string بيعبر عن النص الذى يحويه
الأبناء – وهما العناصر اللذى يحويهم العنصر ومخزنة فى python sequence  تقدر تحصل عليهم بإستدعاء ل getchildren


وال ElementTree بتستخدم لتمثيل هيكلية الElement وتحويلها من والى XML

المهم سيبونا من الكلام دا كله
ملف ال books.xml المعتاد
Code: [Select]
<?xml version="1.0"?>
<computer>
    <library>
        <books>
            <book id="1" class="programming">
                <name>Introduction to Python</name>
                <author>Ahmed Youssef</author>
                <price>80</price>
            </book>
            <book id="2" class="programming">
                <name>Introduction to Java</name>
                <author>Wael Muhammed</author>
                <price>130</price>
            </book>
            <book id="3" class="programming">
                <name>Introduction to Ruby</name>
                <author>Ahmed Youssef</author>
                <price>70</price>
            </book>
            <book id="4" class="programming">
            <name>Introduction to Linux Programming</name>
            <author>Ahmed Mostafa</author>
            <price>90</price>
            </book>
        </books>
    </library>
</computer>

عايزين نحصل على كل عنصر بيحوى كلمة book

الأول نستدعى etree
Code: [Select]
import xml.etree.ElementTree as etree

خلينا نعمل كلاس بيمثل الكتاب
Code: [Select]
class Book(object):
    def report(self):
        for k, v in self.__dict__.items():
            print k, " => ", v
هنضيف ال attributes بعدين

نيجى على المهم الأول نعمل ال tree
Code: [Select]
tree=etree.parse("books.xml")
مرر اسم الملف ل parse وهو هينشئ الtree
Code: [Select]
root=tree.getroot()
نحصل على العنصر الأول فى الملف وهنا هو computer

Code: [Select]
print root.tag
نطبع اسم العنصر دا

تعالى نشوف عنصر تقليدى لل book tag
Code: [Select]
            <book id="1" class="programming">
                <name>Introduction to Python</name>
                <author>Ahmed Youssef</author>
                <price>80</price>
            </book>
لاحظ بيشمل id , class attributes وبيحوى 3 tags هما name, author, price فل
Code: [Select]
def printBook(booktag):
    b=Book()
    b.class_=booktag.attrib['class']
    b.id_=booktag.attrib['id']

    for t in booktag.getchildren():
        if t.tag=="name":
            b.name=t.text
        elif t.tag=="author":
            b.author=t.text
        elif t.tag=="price":
            b.price=int(t.text)
        else:
            pass
           
    b.report()
هنا بنحصل على ال attributes الأول -class, id- من خلال ال attrib dict
وبعد كدا بنعمل لوب سريعة على العناصر اللى بيحويها ال book tag اللى قلنا عليهم name, price, author
ونخزن كل واحد ك attribute فى الكائن b

بس نسينا حاجة احنا هنستدعى printBook دى ازاى اساسا ؟ اه صح
Code: [Select]
def printBooks(root):
    for t in root.getchildren():
        if t.tag == "book":
            printBook(t)
        else:
            printBooks(t)
sweet بس مش فعال شوية  لأننا كل اللى عايزينه هو ال Book element صح ؟
خلاص استخدم getiterator من ال tree وهى هتدور فى كل العناصر وبس ياسيدى
Code: [Select]
def printBooks2(tree):
    for book in tree.getiterator("book"):
        printBook(book)
السورس
Code: [Select]
#!usr/bin/env python

import xml.etree.ElementTree as etree

tree=etree.parse("books.xml")
root=tree.getroot()

print root.tag

class Book(object):
    def report(self):
        for k, v in self.__dict__.items():
            print k, " => ", v
       
           
def printBook(booktag):
    b=Book()
    b.class_=booktag.attrib['class']
    b.id_=booktag.attrib['id']
   
    for t in booktag.getchildren():
        if t.tag=="name":
            b.name=t.text
        elif t.tag=="author":
            b.author=t.text
        elif t.tag=="price":
            b.price=int(t.text)
        else:
            pass
           

   
    b.report()
   
   
def printBooks(root):
    for t in root.getchildren():
        if t.tag == "book":
            printBook(t)
        else:
            printBooks(t)
           
def printBooks2(tree):
    for book in tree.getiterator("book"):
        printBook(book)
       
       
printBooks2(tree)
#printBooks(root)
للمزيد
http://docs.python.org/library/xml.etree.elementtree.html

http://diveintopython3.org/xml.html


« Last Edit: September 11, 2009, 10:15:28 PM by Ahmed Youssef »
Logged

Life is just a chance to grow a soul. - A. Powell
Weblog: http://ahmedyoussef.wordpress.com/

St0rM

  • [C programmer]
  • Administrator
  • Active Member
  • *****
  • Posts: 188
  • Why So serious ?
    • View Profile
    • WWW
    • Email
Re: etree: An Element on a Tree
« Reply #1 on: September 11, 2009, 10:12:22 PM »
an elephant on the tree
Logged

Ahmed Youssef

  • Helping Freak
  • Administrator
  • Active Member
  • *****
  • Posts: 242
    • View Profile
    • WWW
    • Email
Re: التعامل مع ال XML من خلال etree
« Reply #2 on: September 11, 2009, 10:16:17 PM »
Don't play Winning Eleven with an elephant :D
Logged

Life is just a chance to grow a soul. - A. Powell
Weblog: http://ahmedyoussef.wordpress.com/