使用xml.dom.minidom更新XML元素值

有一段XML结构类似于:
在这里插入图片描述

<Store>
   <foo>
      <book>
        <isbn>123456</isbn>
      </book>
      <title>XYZ</title>
      <checkout>no</checkout>
   </foo>

   <bar>
      <book>
        <isbn>7890</isbn>
      </book>
      <title>XYZ2</title>
      <checkout>yes</checkout>
   </bar>
</Store>

需要使用xml.dom.minidom完成以下操作:

  1. 遍历XML文件
  2. 根据父元素查找或获取特定元素,例如,在作者1中查找checkout元素,在作者2中查找isbn元素
  3. 更改/设置该元素的值
  4. 将新的XML结构写入文件

2、解决方案

2.1 导入xml.dom.minidom库

import xml.dom.minidom as DOM

2.2 定义获取单个子元素的函数

def getLoneChild(node, tagname):

  assert ((node is not None) and (tagname is not None))
  elem = node.getElementsByTagName(tagname)
  if ((elem is None) or (len(elem) != 1)):
    return None
  return elem

2.3 定义获取单个叶子的函数

def getLoneLeaf(node, tagname):

  assert ((node is not None) and (tagname is not None))
  elem = node.getElementsByTagName(tagname)
  if ((elem is None) or (len(elem) != 1)):
    return None
  leaf = elem[0].firstChild
  if (leaf is None):
    return None
  return leaf.data

2.4 定义设置checkout的函数

def setcheckout(node, tagname):

  assert ((node is not None) and (tagname is not None))
  child = getLoneChild(node, 'foo')
  Check = getLoneLeaf(child[0],'checkout')
  Check = tagname
  return Check

2.5 解析XML文件

doc = DOM.parse('test.xml')

2.6 获取根元素

root = doc.getElementsByTagName('Store')[0]

2.7 调用setcheckout函数设置checkout元素值

output = setcheckout(root, "yes")

2.8 将新的XML结构写入文件

tmp_config = '/tmp/tmp_config.xml'
fw = open(tmp_config, 'w')
fw.write(doc.toxml())
fw.close()

2.9 代码示例

import xml.dom.minidom as DOM

# find the author as a child of the "Store"
def getAuthor(parent, author):
  # by looking at the children
  for child in [child for child  in parent.childNodes 
                if child.nodeType != DOM.Element.TEXT_NODE]:
    if child.tagName == author:
      return child
  return None

def alterElement(parent, attribute, newValue):
  found = False;
  # look through the child elements, skipping Text_Nodes 
  #(in your example these hold the "values"
  for child in [child for child  in parent.childNodes 
                if child.nodeType != DOM.Element.TEXT_NODE]:

    # if the child element tagName matches target element name
    if child.tagName == attribute:
      # alter the data, i.e. the Text_Node value, 
      # which is the firstChild of the "isbn" element
      child.firstChild.data = newValue
      return True

    else:
      # otherwise look at all the children of this node.
      found = alterElement(child, attribute, newValue)

    if found:
      break 

  # return found status
  return found

doc = DOM.parse("test.xml")
# This assumes that there is only one "Store" in the file
root = doc.getElementsByTagName("Store")[0]

# find the author
# this assumes that there are no duplicate author names in the file
author = getAuthor(root, "foo")
if not author:
  print "Author not found!"
else:
  # alter an element
  if not alterElement(author, "isbn", "987654321"):
    print "isbn not found"
  else:
    # output the xml
    tmp_config = '/tmp/tmp_config.xml'
    f = open(tmp_config, 'w')
    doc.writexml( f )
    f.close()
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值