0

I'm using ElementTree to remove a number of elements from an XML and then write it back.

After writing the file, the labels for the namespaces have all changed.

Because of that, the application that uses the XML doesn't accept the updated file any more.

Is it possible to tell ElementTree to retain the original labels?

For example. This is part of the source XML:

<gnc:account version="2.0.0">
  <act:name>Root Account</act:name>
  <act:id type="guid">9f8f1286bffd64d6dff54385a62b2650</act:id>
  <act:type>ROOT</act:type>
  <act:commodity>
    <cmdty:space>ISO4217</cmdty:space>
    <cmdty:id>NZD</cmdty:id>
  </act:commodity>
  <act:commodity-scu>100</act:commodity-scu>
</gnc:account>

After writing it back:

<ns0:account version="2.0.0">
  <ns5:name>Root Account</ns5:name>
  <ns5:id type="guid">9f8f1286bffd64d6dff54385a62b2650</ns5:id>
  <ns5:type>ROOT</ns5:type>
  <ns5:commodity>
    <ns4:space>ISO4217</ns4:space>
    <ns4:id>NZD</ns4:id>
  </ns5:commodity>
  <ns5:commodity-scu>100</ns5:commodity-scu>
</ns0:account>

The python code I'm using is:

import xml.etree.ElementTree as ET

tree = ET.parse('file1.xml')
root = tree.getroot()
tree.write('file2.xml')

1 Answer 1

1

Switching to lxml made it work:

import lxml.etree as ET

tree = ET.parse(args.infile)
root = tree.getroot()
tree.write(args.outfile,
           xml_declaration=True,encoding='utf-8',
           method="xml")

Now the output is:

<gnc:account version="2.0.0">
  <act:name>Root Account</act:name>
  <act:id type="guid">9f8f1286bffd64d6dff54385a62b2650</act:id>
  <act:type>ROOT</act:type>
  <act:commodity>
    <cmdty:space>ISO4217</cmdty:space>
    <cmdty:id>NZD</cmdty:id>
  </act:commodity>
  <act:commodity-scu>100</act:commodity-scu>
</gnc:account>

... which is exactly the same as the input.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.