Python xml elementtree namespace

How to preserve namespaces when parsing xml via ElementTree in Python

As you can see, the default namespace is changed to ns0 .

Is there any way to solve this problem with ElementTree ?

The dup link uses clearly ET.register_namespace(. . Edit your Question to minimal reproducible example to show how you use it.

@stovfl It’s not about preserving the namespace and didn’t help me. The name space should not be hard coded, it can be xmlns:prefix=»URI» with any prefix and URI.

The only way to preserve the namespace prefix with ElementTree is by using register_namespace() . If you don’t like that, try lxml instead.

1 Answer 1

ElementTree will replace those namespaces’ prefixes that are not registered with ET.register_namespace . To preserve a namespace prefix, you need to register it first before writing your modifications on a file. The following method does the job and registers all namespaces globally,

def register_all_namespaces(filename): namespaces = dict([node for _, node in ET.iterparse(filename, events=['start-ns'])]) for ns in namespaces: ET.register_namespace(ns, namespaces[ns]) 

This method should be called before ET.parse method, so that the namespaces will remain as unchanged,

import xml.etree.ElementTree as ET register_all_namespaces('filename.xml') tree = ET.parse('filename.xml') # XML modification here # save the modifications tree.write('filename.xml') 

Источник

Читайте также:  Php событие при изменении файла
Оцените статью