[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))
原文地址:https://www.cnblogs.com/bicker/p/5247685.html