PythonShowMeTheCode(0017-19): xls轉(zhuǎn)xml

1. 題目

第0017題: 將 第 0014 題中的 student.xls 文件中的內(nèi)容寫到 student.xml 文件中,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<students>
<!--
    學(xué)生信息表
    "id" : [名字, 數(shù)學(xué), 語文, 英文]
-->
{
    "1" : ["張三", 150, 120, 100],
    "2" : ["李四", 90, 99, 95],
    "3" : ["王五", 60, 66, 68]
}
</students>
</root>

2. 實現(xiàn)

# -*- coding: utf-8 -*-
import openpyxl
from lxml import etree
import codecs
from collections import OrderedDict

attr = ["ID", "Name", "Chinese", "Math", "English"]


def xls_to_xml(path):
    if path is None:
        return

    wb = openpyxl.load_workbook(path)
    ws = wb.get_sheet_by_name("Sheet1")

    student_xml = etree.ElementTree(etree.Element("grade"))
    for row in range(1, ws.max_row+1):
        grade_attr = OrderedDict()
        for col in range(1, ws.max_column+1):
            print(ws.cell(row=row, column=col).value)
            grade_attr[attr[col-1]] = str(ws.cell(row=row, column=col).value)

        sub = etree.SubElement(student_xml.getroot(), "GradeAttr", grade_attr)
        sub.tail = "\n"

    output = codecs.open("student.xml", "w", encoding="utf-8")
    output.write(etree.tounicode(student_xml.getroot()))
    output.close()


if __name__ == "__main__":
    xls_to_xml("./student.xlsx")

3. lxml.etree Tutorial中文翻譯

譯自:lxml.etree Tutorial

這是一個使用lxml.etree處理XML的教程。其中,簡要的描述了ElementTree API這一主要概念,并且有一些簡單的擴(kuò)展,希望使你的程序猿道路更加輕松。想要獲取完整的API,請看這里

目錄

一般地,以下面這種方式導(dǎo)入lxml.etree:

from lxml import etree

如果你的代碼僅僅使用了ElementTree API,并且沒有依賴于其他lxml.etree庫的特定方法,你可以參考下面(任意部分的)導(dǎo)入鏈條,來跳轉(zhuǎn)到原始的ElementTree庫。

try:
    from lxml import etree
    print("running with lxml.etree")
except ImportError:
     try: 
          # Python 2.5
          import xml.etree.cElementTree as etree
          print("running with cElementTree on Python 2.5+")
     except ImportError:
          try:
               # Python 2.5
               import xml.etree.ElementTree as etree
               print("running with ElementTree on Python 2.5+")
          except ImportError:
               try:
                    # normal cElementTree install
                    import cElementTree as etree
                    print("running with cElementTree")
               except ImportError:
                    try:
                         # normal ElementTree install
                         import elementtree.ElementTree as etree
                         print("running with ElementTree")
                    except ImportError:
                         print("Failed to import ElementTree from any known place")

本教程幫助編寫可移植的代碼,在例子中,清楚地說明了部分現(xiàn)有的API,是在ElementTree API基礎(chǔ)上的擴(kuò)展。這些定義在Fredrik Lundh's ElementTree library.

0.1 Element類

Element對象是ElementTree API主要的容器對象,大部分操作XML樹的方法都需要通過Element對象訪問。Element對象可以簡單的通過調(diào)用下面Element()方法建立:

root = etree.Element("root")

訪問Element對象的tag屬性,能夠得到XML標(biāo)簽的名字:

print(root.tag)

#輸出:root

Element對象之間是以一個XML樹的結(jié)構(gòu)組織起來的。append()方法可以將Element()方法創(chuàng)建的子Element對象,加入到一個父Element:

root.append(etree.Element("child1"))

然而,還有一個更簡便,更有效率的方法,來實現(xiàn)創(chuàng)建并添加子Element: 使用SubElement方法。這個方法接受與Element()方法一樣的參數(shù)。額外的,SubElement()第一個參數(shù)為parent Element對象。

child2 = etree.SubElement(root, "child2")
child3 = etree.SubElement(root, "child3")

你可以把你建立的這個XML樹打印出來:

print(etree.tostring(root, pretty_print=True))

#輸出:
<root>
    <child1/>
    <child2/>
    <child3/>
</root>

0.2 Element對象們可以看作一個列表

為了使訪問子Element對象更方便直接,Element對象們盡量“拷貝”了Python中l(wèi)ist的行為:

>>> child = root[0]
>>> print(child.tag)
child1

>>> print(len(root))3
>>> root.index(root[1]) # lxml.etree only!1
>>> children = list(root)
>>> for child in root:
...   print(child.tag)
child1
child2
child3

>>> root.insert(0, etree.Element("child0"))
>>> start = root[:1]
>>> end = root[-1:]
>>> print(start[0].tag)
child0

>>> print(end[0].tag)
child3

在ElementTree 1.3和lxml 2.0版本之前,你可以直接判斷一個Element對象是否為真,來看該Element對象是否包含子Element:

if root: # this no longer works!
    print("The root element has children")

這個特性將不再被支持了,很多用戶驚奇的發(fā)現(xiàn)Element對象居然不是“something”,而會是False的,這違背常理。作為替代,可以使用更明確不易出錯的len(Element)。

>>> print(etree.iselement(root)) # test if it's some kind of Element
True

>>> if len(root): # test if it has children
...    print("The root element has children")
The root element has children

還有一個更重要的例子,Element對象在lxml(2.0版本以后)的一些行為背離了Python中的list以及原始的ElementTree(Python2.7/3.2和ElementTree1.3版本之前)。

>>> for child in root:
...    print(child.tag)
child0
child1
child2
child3

>>> root[0] = root[-1] # this moves the element in lxml.etree!
>>> for child in root:
...    print(child.tag)
child3
child1
child2

在上面這個例子中,最后一個Element對象被移到另一個位置,它自動的移除了它所占用的新位置上原來的對象。這一點是不同于list的。在list中,對象可以同時出現(xiàn)在多個位置:

>>> l = [0, 1, 2, 3]
>>> l[0] = l[-1]
>>> l
[3, 1, 2, 3]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 人生苦短,我用Python。 起初,這篇文章是打算來寫 XPath 的,可是后來一想,我需要的僅是 XPath 的...
    Moscow1147閱讀 21,070評論 1 14
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,853評論 18 399
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,697評論 19 139
  • 依賴配置與依賴范圍http://blog.csdn.net/sunnyyoona/article/details/...
    小小機(jī)器人閱讀 326評論 0 0
  • 這些日子就像是一天一天在倒計時 一想到他走了 心里就是說不出的滋味 從幾個月前認(rèn)識他開始 就意識到終究會發(fā)生的 只...
    栗子a閱讀 284評論 1 2

友情鏈接更多精彩內(nèi)容