【问题标题】:How to output XML declaration <?xml version="1.0"?> in Python/ElementTree如何在 Python/ElementTree 中输出 XML 声明 <?xml version="1.0"?>
【发布时间】:2021-02-21 21:45:52
【问题描述】:

我正在尝试为 XML 中的单词参考源文件创建一个 XML 文件。当我写入文件时,只有“xml_decaration=True”它显示&lt;?xml version='1.0' encoding='us-ascii'?&gt;,但我希望它采用&lt;?xml version="1.0"?&gt; 的形式。

from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
import xml.etree.ElementTree as ET
import uuid
from lxml import etree

root=Element('b:sources')
root.set('SelectedStyle','')
root.set('xmlns:b','http://schemas.openxmlformats.org/officeDocument/2006/bibliography')
root.set('xmlns','http://schemas.openxmlformats.org/officeDocument/2006/bibliography')
#root.attrib=('SelectedStyle'='', 'xmlns:b'='"http://schemas.openxmlformats.org/officeDocument/2006/bibliography"', 'xmlns:b'='"http://schemas.openxmlformats.org/officeDocument/2006/bibliography"','xmlns'='"http://schemas.openxmlformats.org/officeDocument/2006/bibliography"')


source=ET.SubElement(root, 'b:source')
ET.SubElement(source,'b:Tag')
ET.SubElement(source,'b:SourceType').text='Misc'
ET.SubElement(source,'b:guid').text=str(uuid.uuid1())

Author=ET.SubElement(source,'b:Author')
Author2=ET.SubElement(Author,'b:Author')
ET.SubElement(Author2,'b:Corporate').text='Norsk olje og gass'

ET.SubElement(source, 'b:Title').text='R-002'
ET.SubElement(source, 'b:Year').text='2019'
ET.SubElement(source, 'b:Month').text='10'
ET.SubElement(source, 'b:Day').text='27'


tree=ElementTree(root)

tree.write('Sources.xml', xml_declaration=True, method='xml')

【问题讨论】:

    标签: python xml character-encoding elementtree


    【解决方案1】:

    ElementTree.write() 有这个签名:

    write(file, encoding="us-ascii", xml_declaration=None, default_namespace=None,
          method="xml", *, short_empty_elements=True)
    

    如果您想要 XML 的默认编码,即 UTF-8,请使用 encoding="" 调用。

    相关:

    【讨论】:

    • 使用 xml_declaration=None 它不会显示任何标题。我需要它来显示&lt;?xml version="1.0"?&gt; ,仅此而已。
    • 不,不要使用xml_declaration=None。我给你看了文档中的签名。签名显示所有可能的参数及其默认值。仅使用您想要更改默认值的那些参数。所以对于xml_declaration 使用xml_declaration=True。不要害怕文档——它是您学习的最佳朋友。 (我在答案中链接了ElementTree.write() 的文档,现在也在这里。)
    猜你喜欢
    • 2014-03-23
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 2020-07-05
    • 2015-07-15
    相关资源
    最近更新 更多