xml的解析和对xml节点里面的值的修改

xml的解析和修改:

 xml的解析就是对xml节点的值的读取.网上有三种读取方式,我采用xml.dom.minidom和xml.etree.cElementTree,现在对于两者的区别不是很了了解.https://www.jb51.net/article/63780.htm这篇文章写的还是相对详细,但是也是主要说明使用方法. http://www.w3school.com.cn/x.asp这个网站有xml的详细介绍.

1.使用xml.dom.minidom解析和修改xml文件:

xml文件:

<object>                     #object是元素,有属性
    <name>guohui</name>      # name 为object子元素
    <pose>Unspecified</pose>
    <truncated>0</truncated>
    <difficult>0</difficult>
    <bndbox>               # bndbox 为object子元素     
      <xmin>885</xmin>       # xmin 为bndbox子元素
      <ymin>429</ymin>
      <xmax>907</xmax>
      <ymax>457</ymax>
    </bndbox>
  </object>
def ReadXml(xmlfile):
    dom = xml.dom.minidom.parse(xmlfile)        #打开xml文档
    root = dom.documentElement               #得到xml文档对象
    tree = ET.parse(xmlfile)
 name =root.getElementsByTagName('name')
 xmin =root.getElementsByTagName('xmin')
 ymin =root.getElementsByTagName('ymin')
 xmax =root.getElementsByTagName('xmax')
 ymax =root.getElementsByTagName('ymax')
    x1 = y1 = 10000
    x2 = y2 = 0                                #读取xmin的数据
    for i in range(len(name)):
        if int(xmin[i].firstChild.data) <= x1:
            x1 = int(xmin[i].firstChild.data)
        if int(ymin[i].firstChild.data) <= y1:
            y1 = int(ymin[i].firstChild.data)
        if int(xmax[i].firstChild.data) >= x2:
            x2 = int(xmax[i].firstChild.data)
        if int(ymax[i].firstChild.data) >= y2:
            y2 = int(ymax[i].firstChild.data)
    results = [x1-30, y1-30, x2+30, y2+30]
    return results, tree

2.使用xml.etree.cElementTree解析和修改xml文件:

def read_xml(xmlname):
  tree = ET.parse(xmlname)
  root = tree.getroot()
  return tree,root
def modify(xmlfile):
    tree, root = read_xml(xmlfile)
    objs = tree.findall('object')
    for obj in objs:
        bbox = obj.find('bndbox')
        if int(bbox.find('xmin').text) >= int(bbox.find('xmax').text):
            bbox.find('xmin').text,bbox.find('xmax').text = bbox.find('xmax').text,bbox.find('xmin').text
            print 'modify x'
        if int(bbox.find('ymin').text) >= int(bbox.find('ymax').text):
            bbox.find('ymin').text,bbox.find('ymax').text = bbox.find('ymax').text,bbox.find('ymin').text
            print 'modify y'
    write_xml(tree,xmlfile)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值