ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python-使用xml.dom.minidom更新元素值

2019-10-24 05:56:24  阅读:418  来源: 互联网

标签:minidom xml python


我有一个类似于以下内容的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)搜索/获取特定元素,具体取决于其父元素

示例:author1的checkout元素,author2的isbn

3)更改/设置该元素的值

4)将新的XML结构写入文件

有人可以帮忙吗?

谢谢!

更新:

这是我到目前为止所做的

import xml.dom.minidom
checkout = "yes"

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

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


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

doc = xml.dom.minidom.parse('test.xml') 
root = doc.getElementsByTagName('Store')[0]
output = setcheckout(root, checkout)

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

解决方法:

我不确定您所说的“结帐”是什么意思.该脚本将找到该元素并更改该元素的值.也许您可以使其适应您的特定需求.

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()

通常的想法是,将作者的名称与“ Store”元素的子代的tagNames进行匹配,然后递归遍历作者的子代,以查找与目标元素tagName的匹配.此解决方案中有许多假设,但可能会让您入门.尝试不使用递归处理XML之类的层次结构是很痛苦的.

干杯,
菲尔

回想起来,“ alterElement”函数中存在错误.我已经解决了这个问题(请注意“找到的”变量”)

标签:minidom,xml,python
来源: https://codeday.me/bug/20191024/1918417.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有