[python小記]使用lxml修改xml文件,並遍歷目錄


  這次的目的是遍歷目錄,把目標文件及相應的目錄信息更新到xml文件中。在經過痛苦的摸索之后,從python自帶的ElementTree投奔向了lxml。而棄用自帶的ElementTree的原因就是,namespace。

  XML命名空間

  作用是為避免元素命名沖突,當出現命名沖突的時候,可以使用前綴來避免命名沖突,就如:

<h:table>
    <h:tr>
    <h:td>App Store</h:td>
    <h:td>Google Play</h:td>
    </h:tr>
</h:table>

  使用命名空間(Namespaces):

<f:table xmlns:f="http://www.w3school.com.cn/furniture">
   <f:name>African Coffee Table</f:name>
   <f:width>80</f:width>
   <f:length>120</f:length>
</f:table>

  添加的xmlns屬性,就會前綴賦予了一個與某個命名空間相關聯的限定名稱


 

   lxml安裝:

  1. 安裝pip
  2. 安裝setuptools: Windows(Powershell3)輸入
    > (Invoke-WebRequest https://bootstrap.pypa.io/ez_setup.py).Content | python -

     

  3. 下載lxml.whl,根據python版本選擇合適的whl下載:地址
  4. 安裝wheel
    pip install wheel

     

  5. 安裝下載好的whl文件
    pip install .\lxml-3.5.0-cp34-none-win_amd64.whl

     


 

  lxml使用:

  lxml的教程網站為:http://lxml.de/index.html

  使用lxml可以這樣import:

from lxml import etree

  導入並解析xml文件:

tree = etree.parse(fileName)

  獲取xml的命名空間:

root = tree.getroot()
nsmap = root.nsmap

  如果xml文件使用的默認命名空間:

>>> nsmap
{None: 'http://schemas.microsoft.com/developer/msbuild/2003'}

  要查找某節點,使用到xpath:

def getNode(tree, node):
    NS_PREFIX = "default"
    root = tree.getroot()
    nsmap = root.nsmap
    nsmap[NS_PREFIX] = nsmap[None]
    nsmap.pop(None)
    return tree.xpath("//{0}:{1}".format(NS_PREFIX, node), namespaces=nsmap)

  添加子節點:

etree.SubElement(node, tag)

  最后寫入到xml文件中:

fileHandler = open(filePath, "wb")
tree.write(fileHandler, encoding="utf-8", xml_declaration=True, pretty_print=True)
fileHandler.close()

 


  xpath基礎

  xpath使用路徑表達式來選取xml文檔中的節點或節點集。

表達式 描述
nodename 從當前節點的子節點中,選取tag為nodename的所有節點
/ 從根節點選取
// 任意位置選取
. 選取當前節點
.. 選取父節點
@att 選取帶屬性att的節點
[] 謂語

  例子:

1 tree.xpath("//Folder[@Include]")
2 #選取帶Include屬性的Folder節點
3 tree.xpath("//ItemGroup[./Folder]")
4 tree.xpath("//ItemGroup[Folder]")
5 #選取含有Folder子節點的ItemGroup節點

 


  遍歷目錄:

  遍歷目錄有兩個方法:os.list_dir與os.walk。各自的用例:

 1 import os
 2 
 3 def list_dir(rootDir):
 4     for lists in os.listdir(rootDir):
 5         path = os.path.join(rootDir, lists)
 6         print(path)
 7         if os.path.isdir(path):
 8             list_dir(path)
 9 
10 def walk(rootDir):
11     for root, dirs, files in os.walk(rootDir):
12         for d in dirs:
13             print(os.path.join(root, d))
14         for f in files:
15             print(os.path.join(root, f))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM