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