如果我想要在Python中创建一个简单的XML文件,有哪些库可以使用?
我想要的XML文件的格式如下:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some vlaue2</field2>
</doc>
</root>
import xml.etree.cElementTree as ET
root = ET.Element("root")
doc = ET.SubElement(root, "doc")
ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"
tree = ET.ElementTree(root)
tree.write("filename.xml")
lxml库包含了一种非常方便的XML生成语法,称为E-factory。以下是我如何创建你提供的示例:
#!/usr/bin/python
import lxml.etree
import lxml.builder
E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2
the_doc = ROOT(
DOC(
FIELD1('some value1', name='blah'),
FIELD2('some value2', name='asdfasd'),
)
)
print lxml.etree.tostring(the_doc, pretty_print=True)
输出:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
它还支持向已有节点添加内容,例如在上述示例后你可以这样说:
the_doc.append(FIELD2('another value again', name='hithere'))
getattr
,例如:getattr(E, "some-tag")
。 - haridsvYattag http://www.yattag.org/ 或者https://github.com/leforestier/yattag 提供了一个有趣的 API 来创建 XML 文档(以及 HTML 文档)。
它使用了上下文管理器和 with
关键字。
from yattag import Doc, indent
doc, tag, text = Doc().tagtext()
with tag('root'):
with tag('doc'):
with tag('field1', name='blah'):
text('some value1')
with tag('field2', name='asdfasd'):
text('some value2')
result = indent(
doc.getvalue(),
indentation = ' '*4,
newline = '\r\n'
)
print(result)
因此,您将获得:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
import string
from xml.sax.saxutils import escape
inner_template = string.Template(' <field${id} name="${name}">${value}</field${id}>')
outer_template = string.Template("""<root>
<doc>
${document_list}
</doc>
</root>
""")
data = [
(1, 'foo', 'The value for the foo document'),
(2, 'bar', 'The <value> for the <bar> document'),
]
inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result
输出:
<root>
<doc>
<field1 name="foo">The value for the foo document</field1>
<field2 name="bar">The <value> for the <bar> document</field2>
</doc>
</root>
<
和>
的转义。我通过从xml.sax
中引入一个实用程序来解决了这个问题。如果你希望选择最简单的方法,我建议使用minidom: http://docs.python.org/library/xml.dom.minidom.html。它是Python标准库中内置的,并且在简单情况下使用起来很直观。
这里有一个非常易懂的教程:http://www.boddie.org.uk/python/XML_intro.html
Harry Potter
J.K. Rowling
1997
29.99
Learning XML
Erik T. Ray
2003
39.95
使用Python的minidom模块解析XML文件并输出所有标题为英文的书籍:from xml.dom import minidom
# 打开XML文档并解析
doc = minidom.parse("books.xml")
# 获取所有名为“book”的元素列表
books = doc.getElementsByTagName("book")
# 遍历每一本书,并输出标题为英文的书籍信息
for book in books:
# 获取书籍标题元素
title = book.getElementsByTagName("title")[0]
# 如果书籍标题语言是英语,则输出书籍信息
if title.getAttribute("lang") == "en":
print("Title: {}".format(title.firstChild.data))
print("Author: {}".format(book.getElementsByTagName("author")[0].firstChild.data))
print("Year: {}".format(book.getElementsByTagName("year")[0].firstChild.data))
print("Price: ${}".format(book.getElementsByTagName("price")[0].firstChild.data))
print("\n")
输出结果:Title: Harry Potter
Author: J.K. Rowling
Year: 1997
Price: $29.99
Title: Learning XML
Author: Erik T. Ray
Year: 2003
Price: $39.95
- Stevoisiak
xml_declaration=True
... 但是,要获得等效的行为,请像这样调用tree.write()
:tree.write("filename.xml", xml_declaration=True, encoding='utf-8')
只要您明确指定一个编码,就可以使用任何编码。(如果您不信任Web服务器的配置,则ascii
将强制实体编码超出7位ASCII集的所有Unicode字符。) - ssokolowvlaue2
改正为value2
的人:原问题中请求的 XML 输出中有错别字。在那个改变之前,这里的错别字实际上是正确的。 - ssokolowcElementTree
在Python 3.3中已被弃用。 - Stevoisiak