Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสร้าง XML Documents พร้อม Namespaces ใน Python

Python built-in xml package ยังไม่รองรับ namespaces ตรงๆ ต้องเพิ่มเป็น attribute ปกติ:

import xml.dom.minidom
doc = xml.dom.minidom.Document()
element = doc.createElementNS('https://hello.world/ns', 'ex:el')
element.setAttribute("xmlns:ex", "https://hello.world/ns")
doc.appendChild(element)
print(doc.toprettyxml())

ได้ XML:

<?xml version="1.0" ?>
<ex:el xmlns:ex="https://example.net/ns"/>