最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解在Python程序中解析并修改XML內(nèi)容的方法

 更新時(shí)間:2015年11月16日 17:12:11   投稿:goldensun  
這篇文章主要介紹了在Python程序中解析并修改XML內(nèi)容的方法,依賴于解析成樹狀結(jié)構(gòu)后的節(jié)點(diǎn)進(jìn)行修改,需要的朋友可以參考下

需求
在實(shí)際應(yīng)用中,需要對(duì)xml配置文件進(jìn)行實(shí)時(shí)修改,

1.增加、刪除 某些節(jié)點(diǎn)

2.增加,刪除,修改某個(gè)節(jié)點(diǎn)下的某些屬性

3.增加,刪除,修改某些節(jié)點(diǎn)的文本

使用xml文檔

<?xml version="1.0" encoding="UTF-8"?>
<framework>
  <processers>
    <processer name="AProcesser" file="lib64/A.so"
      path="/tmp">
    </processer>
    <processer name="BProcesser" file="lib64/B.so" value="fordelete">
    </processer>
    <processer name="BProcesser" file="lib64/B.so2222222"/>

    <services>
      <service name="search" prefix="/bin/search?"
        output_formatter="OutPutFormatter:service_inc">

        <chain sequency="chain1"/>
        <chain sequency="chain2"></chain>
      </service>
      <service name="update" prefix="/bin/update?">
        <chain sequency="chain3" value="fordelete"/>
      </service>
    </services>
  </processers>
</framework>

實(shí)現(xiàn)思想
使用ElementTree,先將文件讀入,解析成樹,之后,根據(jù)路徑,可以定位到樹的每個(gè)節(jié)點(diǎn),再對(duì)節(jié)點(diǎn)進(jìn)行修改,最后直接將其輸出

實(shí)現(xiàn)代碼

#!/usr/bin/python
# -*- coding=utf-8 -*-
# author : wklken@yeah.net
# date: 2012-05-25
# version: 0.1

from xml.etree.ElementTree import ElementTree,Element

def read_xml(in_path):
  '''讀取并解析xml文件
    in_path: xml路徑
    return: ElementTree'''
  tree = ElementTree()
  tree.parse(in_path)
  return tree

def write_xml(tree, out_path):
  '''將xml文件寫出
    tree: xml樹
    out_path: 寫出路徑'''
  tree.write(out_path, encoding="utf-8",xml_declaration=True)

def if_match(node, kv_map):
  '''判斷某個(gè)節(jié)點(diǎn)是否包含所有傳入?yún)?shù)屬性
    node: 節(jié)點(diǎn)
    kv_map: 屬性及屬性值組成的map'''
  for key in kv_map:
    if node.get(key) != kv_map.get(key):
      return False
  return True

#---------------search -----
def find_nodes(tree, path):
  '''查找某個(gè)路徑匹配的所有節(jié)點(diǎn)
    tree: xml樹
    path: 節(jié)點(diǎn)路徑'''
  return tree.findall(path)

def get_node_by_keyvalue(nodelist, kv_map):
  '''根據(jù)屬性及屬性值定位符合的節(jié)點(diǎn),返回節(jié)點(diǎn)
    nodelist: 節(jié)點(diǎn)列表
    kv_map: 匹配屬性及屬性值map'''
  result_nodes = []
  for node in nodelist:
    if if_match(node, kv_map):
      result_nodes.append(node)
  return result_nodes

#---------------change -----
def change_node_properties(nodelist, kv_map, is_delete=False):
  '''修改/增加 /刪除 節(jié)點(diǎn)的屬性及屬性值
    nodelist: 節(jié)點(diǎn)列表
    kv_map:屬性及屬性值map'''
  for node in nodelist:
    for key in kv_map:
      if is_delete:
        if key in node.attrib:
          del node.attrib[key]
      else:
        node.set(key, kv_map.get(key))

def change_node_text(nodelist, text, is_add=False, is_delete=False):
  '''改變/增加/刪除一個(gè)節(jié)點(diǎn)的文本
    nodelist:節(jié)點(diǎn)列表
    text : 更新后的文本'''
  for node in nodelist:
    if is_add:
      node.text += text
    elif is_delete:
      node.text = ""
    else:
      node.text = text

def create_node(tag, property_map, content):
  '''新造一個(gè)節(jié)點(diǎn)
    tag:節(jié)點(diǎn)標(biāo)簽
    property_map:屬性及屬性值map
    content: 節(jié)點(diǎn)閉合標(biāo)簽里的文本內(nèi)容
    return 新節(jié)點(diǎn)'''
  element = Element(tag, property_map)
  element.text = content
  return element

def add_child_node(nodelist, element):
  '''給一個(gè)節(jié)點(diǎn)添加子節(jié)點(diǎn)
    nodelist: 節(jié)點(diǎn)列表
    element: 子節(jié)點(diǎn)'''
  for node in nodelist:
    node.append(element)

def del_node_by_tagkeyvalue(nodelist, tag, kv_map):
  '''同過(guò)屬性及屬性值定位一個(gè)節(jié)點(diǎn),并刪除之
    nodelist: 父節(jié)點(diǎn)列表
    tag:子節(jié)點(diǎn)標(biāo)簽
    kv_map: 屬性及屬性值列表'''
  for parent_node in nodelist:
    children = parent_node.getchildren()
    for child in children:
      if child.tag == tag and if_match(child, kv_map):
        parent_node.remove(child)

if __name__ == "__main__":
  #1. 讀取xml文件
  tree = read_xml("./test.xml")

  #2. 屬性修改
   #A. 找到父節(jié)點(diǎn)
  nodes = find_nodes(tree, "processers/processer")
   #B. 通過(guò)屬性準(zhǔn)確定位子節(jié)點(diǎn)
  result_nodes = get_node_by_keyvalue(nodes, {"name":"BProcesser"})
   #C. 修改節(jié)點(diǎn)屬性
  change_node_properties(result_nodes, {"age": "1"})
   #D. 刪除節(jié)點(diǎn)屬性
  change_node_properties(result_nodes, {"value":""}, True)

  #3. 節(jié)點(diǎn)修改
   #A.新建節(jié)點(diǎn)
  a = create_node("person", {"age":"15","money":"200000"}, "this is the firest content")
   #B.插入到父節(jié)點(diǎn)之下
  add_child_node(result_nodes, a)

  #4. 刪除節(jié)點(diǎn)
    #定位父節(jié)點(diǎn)
  del_parent_nodes = find_nodes(tree, "processers/services/service")
    #準(zhǔn)確定位子節(jié)點(diǎn)并刪除之
  target_del_node = del_node_by_tagkeyvalue(del_parent_nodes, "chain", {"sequency" : "chain1"})

  #5. 修改節(jié)點(diǎn)文本
    #定位節(jié)點(diǎn)
  text_nodes = get_node_by_keyvalue(find_nodes(tree, "processers/services/service/chain"), {"sequency":"chain3"})
  change_node_text(text_nodes, "new text")

  #6. 輸出到結(jié)果文件
  write_xml(tree, "./out.xml")

修改后的結(jié)果

<?xml version='1.0' encoding='utf-8'?>
<framework>
  <processers>
    <processer file="lib64/A.so" name="AProcesser" path="/tmp">
    </processer>
    <processer age="1" file="lib64/B.so" name="BProcesser">
      <person age="15" money="200000">this is the firest content</person>
    </processer>
    <processer age="1" file="lib64/B.so2222222" name="BProcesser">
      <person age="15" money="200000">this is the firest content</person>
    </processer>

    <services>
      <service name="search" output_formatter="OutPutFormatter:service_inc"
        prefix="/bin/search?">

        <chain sequency="chain2" />
      </service>
      <service name="update" prefix="/bin/update?">
        <chain sequency="chain3" value="fordelete">new text</chain>
      </service>
    </services>
  </processers>
</framework>

相關(guān)文章

  • 使用Python連接SQLite數(shù)據(jù)庫(kù)的操作步驟

    使用Python連接SQLite數(shù)據(jù)庫(kù)的操作步驟

    SQLite是一種輕量級(jí)的嵌入式數(shù)據(jù)庫(kù),廣泛應(yīng)用于各種應(yīng)用程序中,Python提供了內(nèi)置的sqlite3模塊,使得連接和操作SQLite數(shù)據(jù)庫(kù)變得非常簡(jiǎn)單,本文給大家介紹了使用Python連接SQLite數(shù)據(jù)庫(kù)的操作步驟,需要的朋友可以參考下
    2024-12-12
  • python實(shí)現(xiàn)爬山算法的思路詳解

    python實(shí)現(xiàn)爬山算法的思路詳解

    爬山算法會(huì)收斂到局部最優(yōu),解決辦法是初始值在定義域上隨機(jī)取亂數(shù)100次,總不可能100次都那么倒霉。這篇文章主要介紹了python實(shí)現(xiàn)爬山算法的思路詳解,需要的朋友可以參考下
    2019-04-04
  • python 實(shí)現(xiàn)多進(jìn)程日志輪轉(zhuǎn)ConcurrentLogHandler

    python 實(shí)現(xiàn)多進(jìn)程日志輪轉(zhuǎn)ConcurrentLogHandler

    這篇文章主要介紹了python 實(shí)現(xiàn)多進(jìn)程日志輪轉(zhuǎn)ConcurrentLogHandler,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-03-03
  • python字典進(jìn)行運(yùn)算原理及實(shí)例分享

    python字典進(jìn)行運(yùn)算原理及實(shí)例分享

    在本篇文章里小編給大家整理的是一篇關(guān)于python字典進(jìn)行運(yùn)算原理及實(shí)例分享內(nèi)容,有需要的朋友們可以測(cè)試下。
    2021-08-08
  • python列表操作實(shí)例

    python列表操作實(shí)例

    這篇文章主要介紹了python列表操作方法,實(shí)例分析了Python針對(duì)列表操作的插入、刪除等各種操作技巧,需要的朋友可以參考下
    2015-01-01
  • python獲取交互式ssh shell的方法

    python獲取交互式ssh shell的方法

    今天小編就為大家分享一篇python獲取交互式ssh shell的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-02-02
  • Python進(jìn)階之如何快速將變量插入有序數(shù)組

    Python進(jìn)階之如何快速將變量插入有序數(shù)組

    在我們學(xué)習(xí)python的過(guò)程中,學(xué)習(xí)序列是一門必修課。本文我們就來(lái)一起看一看Python是如何快速將變量插入有序數(shù)組的,感興趣的可以了解一下
    2023-04-04
  • python數(shù)據(jù)預(yù)處理方式 :數(shù)據(jù)降維

    python數(shù)據(jù)預(yù)處理方式 :數(shù)據(jù)降維

    今天小編就為大家分享一篇python數(shù)據(jù)預(yù)處理方式 :數(shù)據(jù)降維,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-02-02
  • Python中Scrapy爬蟲圖片處理詳解

    Python中Scrapy爬蟲圖片處理詳解

    這篇文章主要介紹了Python中Scrapy爬蟲圖片處理方式和原理,需要的朋友學(xué)習(xí)參考下吧。
    2017-11-11
  • Django操作cookie的實(shí)現(xiàn)

    Django操作cookie的實(shí)現(xiàn)

    很多網(wǎng)站都會(huì)使用Cookie。本文主要介紹了Django操作cookie的實(shí)現(xiàn),結(jié)合實(shí)例形式詳細(xì)分析了Django框架針對(duì)cookie操作的各種常見技巧與操作注意事項(xiàng),需要的朋友可以參考下
    2021-05-05

最新評(píng)論

柘荣县| 融水| 夏河县| 武陟县| 巴林左旗| 泽普县| 北辰区| 东方市| 丰原市| 沂源县| 繁昌县| 巧家县| 长汀县| 滦平县| 和顺县| 华容县| 雷山县| 洮南市| 洪江市| 合水县| 宁武县| 建湖县| 漳平市| 长沙市| 陕西省| 商都县| 清水河县| 灌南县| 卢龙县| 罗城| 玉溪市| 龙陵县| 田阳县| 安国市| 成安县| 连平县| 锦屏县| 古丈县| 沙河市| 揭东县| 正阳县|