python 下xml和dict相互转化,含attributes

from lxml import etree

def dictlist(node):
 res = {}
 res[node.tag] = []
 xmltodict(node,res[node.tag])
 reply = {}
 reply[node.tag] = {'value':res[node.tag],'attributes':node.attrib}
 
 return reply

def xmltodict(node,res):
 rep = {}
 
 if len(node):
  #n = 0
  for n in list(node):
   rep[node.tag] = []
   value = xmltodict(n,rep[node.tag])
   if len(n):
   
    value = {'value':rep[node.tag],'attributes':n.attrib}
    #print value
    res.append({n.tag:value})
   else :
    #print rep[node.tag][0]
    res.append(rep[node.tag][0])
   
 else:
  value = {}
  value = {'value':node.text,'attributes':node.attrib}
  #print value
  res.append({node.tag:value})
 
 return
def fromstring(strdict=None):
 root = etree.fromstring(strdict)
 return dictlist(root)

def parse(filename=None):
 tree = etree.parse(filename)
 return dictlist(tree.getroot())
 

def main():
 tree = etree.parse('test.xml')
 print tree
 res = dictlist(tree.getroot())
 print res 
 
def dict2xml(d):
 from xml.sax.saxutils import escape
 def unicodify(o):
  if o is None:
   return u'';
  return unicode(o)
 lines = ["<?xml version=/"1.0/" encoding=/"utf-8/"?>"]
 def addDict(node, offset):
  for name, value in node.iteritems():
   if name == "attributes":
    strqq = lines[len(lines)-1]
    index = strqq.find(u"<")
    strqq = strqq[index+1:len(strqq)-1]
    for x,y in value.iteritems():
     strqq = strqq + u" " *4 + u"%s='%s'"%(x,y)
    lines[len(lines)-1] = u" " * index + u"<%s>"%(strqq)
   else:
    if isinstance(value, dict):
     lines.append(offset + u"<%s>" % name)
     addDict(value, offset + u" " * 4)
     lines.append(offset + u"</%s>" % name)
    elif isinstance(value, list):
     for item in value:
      if isinstance(item, dict):
       addDict(item, offset + u" " * 4)
      else:
       lines.append(offset + u"<%s>%s</%s>" % (name, escape(unicodify(item)), name))
    else:
     if value != "":
      pass
 addDict(d, u"")
 lines.append(u"")
 return u"/n".join(lines)   
    
#if __name__ == '__main__' :
# main()

test 就不帮大家写了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值