Programatically clean/ignore namespaces in XML

I'm trying to write a simple program to read my financial XML files from GNUCash, and learn Python in the process.

The XML looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<gnc-v2
     xmlns:gnc="http://www.gnucash.org/XML/gnc"
     xmlns:act="http://www.gnucash.org/XML/act"
     xmlns:book="http://www.gnucash.org/XML/book"
     {...}
     xmlns:vendor="http://www.gnucash.org/XML/vendor">
<gnc:count-data cd:type="book">1</gnc:count-data>
<gnc:book version="2.0.0">
<book:id type="guid">91314601aa6afd17727c44657419974a</book:id>
<gnc:count-data cd:type="account">80</gnc:count-data>
<gnc:count-data cd:type="transaction">826</gnc:count-data>
<gnc:count-data cd:type="budget">1</gnc:count-data>
<gnc:commodity version="2.0.0">
  <cmdty:space>ISO4217</cmdty:space>
  <cmdty:id>BRL</cmdty:id>
  <cmdty:get_quotes/>
  <cmdty:quote_source>currency</cmdty:quote_source>
  <cmdty:quote_tz/>
</gnc:commodity>

Right now, i'm able to iterate and get results using

import xml.etree.ElementTree as ET 
r = ET.parse("file.xml").findall('.//') 

after manually cleaning the namespaces, but I'm looking for a solution that could either read the entries regardless of their namespaces OR remove the namespaces before parsing.

Note that I'm a complete noob in python, and I've read: Python and GnuCash: Extract data from GnuCash files, Cleaning an XML file in Python before parsing and python: xml.etree.ElementTree, removing "namespaces" along with ElementTree docs and I'm still lost...

I've come up with this solution:

def strip_namespaces(self, tree):

    nspOpen = re.compile("<w*:", re.IGNORECASE)
    nspClose = re.compile("</w*:", re.IGNORECASE)

    for i in tree:
        start = re.sub(nspOpen, '<', tree.tag)          
        end = re.sub(nspOpen, '</', tree.tag)

    # pprint(finaltree)
    return

But i'm failing to apply it. I can't seem to be able to retrieve the tag names as they appear on the file.

链接地址: http://www.djcxy.com/p/58798.html

上一篇: XML解析与Python元素树

下一篇: 以编程方式清除/忽略XML中的名称空间