我需要使用 Python 创建一个 XML 文档,但我无法弄清楚如何添加一个
<?xml version="1.0" encoding="utf-8"?>
Run Code Online (Sandbox Code Playgroud)
以及如何将命名空间元素添加到文档标签
<Document xmlns="urn:iso:std:iso:2013:008.001.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<page1 xmlns="urn:iso:std:iso:2013:008.001.02" </page1>
</Document>
Run Code Online (Sandbox Code Playgroud)
任何例子请
要输出 xml 声明<?xml version="1.0" encoding="utf-8"?>,请使用lxml.etree.tostringwithxml_declaration=True, encoding='utf-8'作为参数。
要添加命名空间元素,请nsmap在创建元素时传递参数。
>>> import lxml.etree
>>>
>>> nsmap = {
... None: "urn:iso:std:iso:2013:008.001.02",
... 'xsi': "http://www.w3.org/2001/XMLSchema-instance",
... }
>>> root = lxml.etree.Element('Document', nsmap=nsmap)
>>> lxml.etree.SubElement(root, 'page1')
<Element page1 at 0x2ad8af8>
>>> print lxml.etree.tostring(root, xml_declaration=True, encoding='utf-8', pretty_print=True)
<?xml version='1.0' encoding='utf-8'?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:2013:008.001.02">
<page1/>
</Document>
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1704 次 |
| 最近记录: |