【发布时间】:2011-10-23 16:05:04
【问题描述】:
我有一个巨大的 xml 文件 (1 Gig)。我想将一些元素(条目)移动到具有相同标题和规范的另一个文件中。
假设原始文件包含带有标签<to_move>的条目:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE some SYSTEM "some.dtd">
<some>
...
<to_move date="somedate">
<child>some text</child>
...
...
</to_move>
...
</some>
我使用 lxml.etree.iterparse 来遍历文件。工作正常。当我找到带有标签<to_move> 的元素时,假设它存储在变量element 中,我这样做了
new_file.write(etree.tostring(element))
但这会导致
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE some SYSTEM "some.dtd">
<some>
...
<to_move xmlns:="some" date="somedate"> # <---- Here is the problem. I don't want the namespace.
<child>some text</child>
...
...
</to_move>
...
</some>
所以问题是:如何告诉 etree.tostring() 不要写 xmlns:="some"。这可能吗?我在 lxml.etree 的 api-documentation 中苦苦挣扎,但找不到令人满意的答案。
这是我为etree.trostring找到的:
tostring(element_or_tree, encoding=None, method="xml",
xml_declaration=None, pretty_print=False, with_tail=True,
standalone=None, doctype=None, exclusive=False, with_comments=True)
将元素序列化为其 XML 的编码字符串表示 树。
对我来说,tostring() 的每个参数似乎都没有帮助。有什么建议或更正吗?
【问题讨论】:
标签: python namespaces lxml tostring elementtree