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

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

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

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

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

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

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

使用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>

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

實現(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):
  '''判斷某個節(jié)點是否包含所有傳入?yún)?shù)屬性
    node: 節(jié)點
    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):
  '''查找某個路徑匹配的所有節(jié)點
    tree: xml樹
    path: 節(jié)點路徑'''
  return tree.findall(path)

def get_node_by_keyvalue(nodelist, kv_map):
  '''根據(jù)屬性及屬性值定位符合的節(jié)點,返回節(jié)點
    nodelist: 節(jié)點列表
    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é)點的屬性及屬性值
    nodelist: 節(jié)點列表
    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):
  '''改變/增加/刪除一個節(jié)點的文本
    nodelist:節(jié)點列表
    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):
  '''新造一個節(jié)點
    tag:節(jié)點標(biāo)簽
    property_map:屬性及屬性值map
    content: 節(jié)點閉合標(biāo)簽里的文本內(nèi)容
    return 新節(jié)點'''
  element = Element(tag, property_map)
  element.text = content
  return element

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

def del_node_by_tagkeyvalue(nodelist, tag, kv_map):
  '''同過屬性及屬性值定位一個節(jié)點,并刪除之
    nodelist: 父節(jié)點列表
    tag:子節(jié)點標(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é)點
  nodes = find_nodes(tree, "processers/processer")
   #B. 通過屬性準(zhǔn)確定位子節(jié)點
  result_nodes = get_node_by_keyvalue(nodes, {"name":"BProcesser"})
   #C. 修改節(jié)點屬性
  change_node_properties(result_nodes, {"age": "1"})
   #D. 刪除節(jié)點屬性
  change_node_properties(result_nodes, {"value":""}, True)

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

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

  #5. 修改節(jié)點文本
    #定位節(jié)點
  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ù)庫的操作步驟

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

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

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

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

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

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

    python字典進行運算原理及實例分享

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

    python列表操作實例

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

    python獲取交互式ssh shell的方法

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

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

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

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

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

    Python中Scrapy爬蟲圖片處理詳解

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

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

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

最新評論

重庆市| 渝中区| 宁津县| 东乌| 杭州市| 阳信县| 沛县| 青龙| 叙永县| 汝南县| 清流县| 讷河市| 佛坪县| 江陵县| 怀来县| 宿州市| 尚义县| 珠海市| 望奎县| 洛隆县| 清流县| 晴隆县| 临汾市| 桂林市| 封丘县| 宁河县| 修武县| 南木林县| 民和| 万山特区| 大城县| 莱州市| 正安县| 怀来县| 利辛县| 临武县| 巴中市| 神木县| 宕昌县| 台中市| 尚志市|