python lxml库生成xml文件-节点命名空间问题


lxml库,处理xml很强大,官方文档:https://lxml.de/tutorial.html#namespaces

例如:

我们要生成如下格式的报文:

<ttt:jesson xmlns:ttt="http://www.hellojesson/ttt" guid="33344555677777777777" version="1.0" xsi="http://www.hahaha.com">
  <ttt:order>
    <ttt:orderhead>
      <ttt:guid/>
    </ttt:orderhead>
  </ttt:order>
</ttt:jesson>

就可以参考如下的样例代码实现:

# 导入库
import lxml.etree as etree

# 注册指定命名空间
etree.register_namespace("ttt", "http://www.hellojesson/ttt")
# 生成根节点 root
= etree.Element("{http://www.hellojesson/ttt}jesson", xsi="http://www.hahaha.com", guid="33344555677777777777", version="1.0") # 生成子节点: order = etree.SubElement(root, "{http://www.hellojesson/ttt}order") orderhead = etree.SubElement(order, "{http://www.hellojesson/ttt}orderhead") guid = etree.SubElement(orderhead, "{http://www.hellojesson/ttt}guid") # 节点赋值 order.text = "text" orderhead.text = "111" guid.text = "hello nihao" # 输出 查看效果 print(etree.tostring(root, pretty_print=True))

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM