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

5
  • Namespace prefixes matter only because of the namespace URI to which they're bound. The actual value of a namespace prefix is otherwise insignificant. Commented Feb 11, 2019 at 18:38
  • @kjhughesso what is the duplicate? It matter because I need to save the xml to file and pass it along. Commented Feb 11, 2019 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. Commented Feb 11, 2019 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. Commented Feb 11, 2019 at 19:20
  • You'll have to register the namespace. Here's a better duplicate: stackoverflow.com/questions/31805606/… Commented Feb 11, 2019 at 19:40

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.