python lxml写xml

3 篇文章 0 订阅
# _*_ coding :'utf-8' _*_
'''
Created on 2013-8-13

@author: nohack
'''

from lxml import etree
#import xml.etree.ElementTree as etree


if __name__ == '__main__':
    #root = etree.Element("root")
    
    root = etree.Element("root",nsmap={'xsi': 'http://b.c/d'})

    root.set("xsiinteresting", "totally")
    child1 = etree.SubElement(root, "child1" )
    child1.set("interesting", "totally")
    child1.text = "TEXT"
    
    child2 = etree.SubElement(root, "child2") 
    child2.set("Attr1", "myattr1")
    child2.set("Attr2", "myattr2")
    
    child3 = etree.SubElement(child2, "child3")
    child3.text = "TEXT"
    child4 = etree.SubElement(child2, "child4")
    child4.text = "TEXT"
    child5 = etree.SubElement(child2, "child5")
    
    child6 = etree.SubElement(child5, "child6")
    child6.text = "TEXT"
    child7 = etree.SubElement(child5, "child7")
    child7.text = "TEXT"
    #root.append( etree.Element("child1") )
    #root.append( etree.Element("child1", interesting="totally"))
    #child2 = etree.SubElement(root, "child2") 

    #child3 = etree.SubElement(root, "child3")
    #root.insert(0, etree.Element("child0")) 
     
    print etree.tostring(root, pretty_print=True) 
    
    # write to file:  
    tree = etree.ElementTree(root)  
    tree.write('TEST.xml', pretty_print=True, xml_declaration=True, encoding='utf-8')  


theTEST.xml file :

<root xmlns:xsi="http://b.c/d" xsiinteresting="totally">
  <child1 interesting="totally">TEXT</child1>
  <child2 Attr1="myattr1" Attr2="myattr2">
    <child3>TEXT</child3>
    <child4>TEXT</child4>
    <child5>
      <child6>TEXT</child6>
      <child7>TEXT</child7>
    </child5>
  </child2>
</root>

文件后缀名有几种可选的方式,但不可自定义,c++调用python解析xml时,会因为from lxml import etree出错,暂时未来得及解决




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值