1

I am trying to parse and write XML using Python's standard library for xml parsing.

The format of the xml is as follows:

xml = '<class:Classification xmlns:class="schema:SpeciesClassification:2.0" xmlns="http://www.w3.org/1999/xhtml" dateClassified="2019-02-11" endangeredMarking="false" caveat="false"></class:Classification>'

When I parse this xml then push it back to a string, I get something strange. All the class: become ns0. How do I keep these markings?


from xml.etree.cElementTree import Element, SubElement, parse, tostring, fromstring

print(tostring(fromstring(xml)))
b'<ns0:Classification xmlns:ns0="schema:SpeciesClassification:2.0" caveat="false" dateClassified="2019-02-11" endangeredMarking="false" />'

Do I have to specify a different parser? I'm just a bit lost on why this gets dropped.

Thanks

code base 5000
  • 3,812
  • 13
  • 44
  • 73
  • Namespace prefixes matter only because of the namespace URI to which they're bound. The actual value of a namespace prefix is otherwise insignificant. – kjhughes Feb 11 '19 at 18:38
  • @kjhughesso what is the duplicate? It matter because I need to save the xml to file and pass it along. – code base 5000 Feb 11 '19 at 18:57
  • @kjhughes your posts do not show a duplicate to my question. I completely disagree the namespaces are 100% needed when reading/writing to files. – code base 5000 Feb 11 '19 at 18:59
  • `ns0` and `class` in your XML are namespace ***prefixes***, not *namespaces*. Namespace prefixes do not matter; only the namespaces to which they're bound matter. In your case, `ns0` and `class` are both bound to `schema:SpeciesClassification:2.0`, so they are equivalent. No conformant XML parser or application will care which namespace *prefix* is used as long as it's bound to the correct *namespace*, and neither should you. – kjhughes Feb 11 '19 at 19:20
  • You'll have to register the namespace. Here's a better duplicate: https://stackoverflow.com/questions/31805606/saving-xml-using-etree-in-python-its-not-retaining-namespaces-and-adding-ns0 – Daniel Haley Feb 11 '19 at 19:40

0 Answers0