如何在转储时删除ns0标记

时间:2014-03-14 16:50:22

标签: python xml python-3.x elementtree

我尝试使用lxml iterparse解析文件,因为实际文件很大。我有以下代码:

import xml.etree.cElementTree as etree
filename = r'D:\test\Books.xml'
context = iter(etree.iterparse(filename, events=('start', 'end')))
_, root = next(context)
for event, elem in context:
    if event == 'start' and elem.tag == '{http://www.book.org/Book-19200/biblography}Book':
        print(etree.dump(elem))
        root.clear()

我的XML看起来像这样:

<Books>
    <Book xmlns="http://www.book.org/Book-19200/biblography"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    ISBN="519292296"
    xsi:schemaLocation="http://www.book.org/Book-19200/biblography ../../book.xsd 
    http://www.w3.org/2000/12/xmldsig# ../../xmldsig-core-schema.xsd">
        <Detail ID="67">
            <BookName>Code Complete 2</BookName>
            <Author>Steve McConnell</Author>
            <Pages>960</Pages>
            <ISBN>0735619670</ISBN>        
            <BookName>Application Architecture Guide 2</BookName>
            <Author>Microsoft Team</Author>
            <Pages>496</Pages>
            <ISBN>073562710X</ISBN>
        </Detail>
    </Book>
    <Book xmlns="http://www.book.org/Book-19200/biblography"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    ISBN="519292296"
    xsi:schemaLocation="http://www.book.org/Book-19200/biblography ../../book.xsd 
    http://www.w3.org/2000/12/xmldsig# ../../xmldsig-core-schema.xsd">
        <Detail ID="87">
            <BookName>Rocking Python</BookName>
            <Author>Guido Rossum</Author>
            <Pages>960</Pages>
            <ISBN>0735619690</ISBN>
            <BookName>Python Rocks</BookName>
            <Author>Microsoft Team</Author>
            <Pages>496</Pages>
            <ISBN>073562710X</ISBN>
        </Detail>
    </Book>
</Books>

运行上面的内容会生成以下内容:

<ns0:Book xmlns:ns0="http://www.book.org/Book-19200/biblography" xmlns:xsi="http://www.w3.org/2001/XMLSchema-ins
ance" ISBN="519292296" xsi:schemaLocation="http://www.book.org/Book-19200/biblography ../../book.xsd      http:/
www.w3.org/2000/12/xmldsig# ../../xmldsig-core-schema.xsd">
        <ns0:Detail ID="67">
            <ns0:BookName>Code Complete 2</ns0:BookName>
            <ns0:Author>Steve McConnell</ns0:Author>
            <ns0:Pages>960</ns0:Pages>
            <ns0:ISBN>0735619670</ns0:ISBN>
            <ns0:BookName>Application Architecture Guide 2</ns0:BookName>
            <ns0:Author>Microsoft Team</ns0:Author>
            <ns0:Pages>496</ns0:Pages>
            <ns0:ISBN>073562710X</ns0:ISBN>
        </ns0:Detail>
    </ns0:Book>

如何确保在没有ns0前缀的情况下打印xml片段?我使用的是Python 3。

1 个答案:

答案 0 :(得分:1)

添加

etree.register_namespace("", "http://www.book.org/Book-19200/biblography")

到你的程序。此函数注册用于序列化的名称空间前缀(在这种情况下,它表示没有前缀)。

参考:http://docs.python.org/3.3/library/xml.etree.elementtree.html#xml.etree.ElementTree.register_namespace