zedz01 zedz01 - 6 months ago 31
Python Question

Python XML iterparse() namespacing

According to this post, I successfully can parse my XML file, and reading it's content. However, if I add namespace to it, the whole thing goes wrong.

Let's consider the following XML:

<root xmlns="MyNamespace">
<A1>
<B1></B1>
<C>1<D1></D1></C>
<E1></E1>
</A1>
<A2>
<B2></B2>
<C>2<D></D></C>
<E2></E2>
</A2>
</root>


My iterparse looks like this:

context = ET.iterparse('../in/process/teszt.xml', events=('end', ), tag='B1')


I found several examples, but to be honest I don't really understand them, and have no idead how to solve this problem.

Answer

In case of XML with default namespace, you need to use the namespace URI along with the element's local name in tag :

context = ET.iterparse('../in/process/teszt.xml', events=('end', ), tag='{MyNamespace}B1')
Comments