I'm working with an XML file which represent an UML model. Here is an example of what it is:

<?xml version="1.0" encoding="utf-8"?>
<XMI xmi.version="1.1" xmlns:UML="omg.org/UML13">
 <XMI.content>
  <UML:Model name="Model" xmi.id="_0">
   <UML:Namespace.ownedElement>
    <UML:Package name="Standard" xmi.id="_5">
     </UML:Package>
   </UML:Namespace.ownedElement>
   </UML:Model>
 </XMI.content>
</XMI>

It is a Rhapsody import format.

I want to modify this XML file by using ElementTree in Python 2.5.

I have at least one problem but I found 2 consequences, here they are:

With this simple code:

import xml.etree.ElementTree as ET
tree = ET.parse('source.xml')
root = tree.getroot()
tree.write('output.xml')

The output is: (and I don't wanted any change)

<XMI xmi.version="1.1">
   <XMI.content>
      <ns0:Model name="FPLN_Model" xmi.id="_0" xmlns:ns0="omg.org/UML13">
         <ns0:Namespace.ownedElement>
            <ns0:Package name="Standard" xmi.id="_5">
            </ns0:Package>
         </ns0:Namespace.ownedElement>
      </ns0:Model>
   </XMI.content>
</XMI>

I searched about this problem and I found a topic on stackoverflow that said to add

ET.register_namespace("UML", "omg.org/UML13")

But an error occur:

AttributeError: 'module' object has no attribute 'register_namespace'

The second consequence is that with a code like the following:

for Package_Node in Temp_Node.find('UML:Package'):

I get the error: SyntaxError: expected path separator (:)

Have someone an idea to help me?

Thank you!

有帮助吗?

解决方案 2

register_namespace is only available since Python 2.7

There might be another way to preserve namespaces with ElementTree in 2.5, but I'm not aware of it.

Alternatively, you could try another parsing library. lxml preserves namespaces and its API is compatible with ElementTree.

其他提示

see this page:http://effbot.org/zone/element-namespaces.htm

ElementTree 1.3 (Python 2.7)

ET.register_namespace(prefix, uri)

ElementTree 1.2 (Python 2.5)

ET._namespace_map[uri] = prefix

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top