使用命名空间创建 XML 文档

Creating XML document with namespace

我正在尝试使用 xml.dom.minidom 生成 XML 文档。

我需要得到的:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns3:loginResponse xmlns:ns2="url1" xmlns:ns3="url2"><ns3:return>abcxyz</ns3:return></ns3:loginResponse>

我试过这个:

import xml.dom.minidom

doc = xml.dom.minidom.Document()
element = doc.createElementNS('url', 'ns25:getSecurityEvents')
element.setAttribute("xmlns:ns25","url")
main = doc.createElement('Text')eNode('Some text here')
main.appendChild(doc.createTextNode('Some text here'))
element.appendChild(main)
doc.appendChild(element)
print(doc.toprettyxml())

但我得到的输出是这样的:

<ns25:getSecurityEvents xmlns:ns25="http://ws.v1.service.resource.manager.product.arcsight.com//securityEventService/">
<Text>Some text here</Text>
</ns25:getSecurityEvents>

我需要完成两件事:

  1. 根节点中的多个命名空间声明

  2. 子节点应该像<ns25:Text>Some text</ns25:Text>

在 minidom 中,名称空间被视为属性。你可以这样做:

import xml.dom.minidom

doc = xml.dom.minidom.Document()

doc_elem = doc.createElement('getSecurityEvents')
doc_elem.setAttribute('xmlns', 'http://ws.v1.service.resource.manager.product.arcsight.com//securityEventService/')
doc.appendChild(doc_elem)

text = doc.createElement('Text')
text.appendChild(doc.createTextNode('Some text here'))
doc_elem.appendChild(text)

print(doc.toprettyxml())

打印

<getSecurityEvents xmlns="http://ws.v1.service.resource.manager.product.arcsight.com//securityEventService/">
    <Text>Some text here</Text>
</getSecurityEvents>

这实际上就是您想要的。如果所有元素都应位于同一个命名空间中,您可以将其设为 默认命名空间 并删除命名空间前缀。此处,<Text><getSecurityEvents>.

位于同一命名空间中

当你想将它写入文件时,使用类似这样的东西(以二进制模式和显式设置编码写入):

with open('filename.xml', 'wb') as xml_file:
    xml_file.write(doc.toxml('utf-8')) 

这确保添加了正确的 XML 声明并且文件编码正确。