xml.etree.ElementTree - Trouble setting xmlns = '...'
Asked Answered
L

1

3

I must be missing something. I'm attempting to set up a google product feed, but am having a hard time registering the namespace.

Example:

Directions here: https://support.google.com/merchants/answer/160589

Trying to insert:

<rss version="2.0" 
xmlns:g="http://base.google.com/ns/1.0">

This is the code:

from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement, Comment, tostring

tree = ElementTree
tree.register_namespace('xmlns:g', 'http://base.google.com/ns/1.0')
top = tree.Element('top')
#... more code and stuff

After code is run, everything turns out fine, but we're missing the xmlns=

I find it easier to create XML docs in php, but I figured I'd give this a try. Where am I going wrong?

On that note, perhaps there is a more appropriate way to do this in python, not using etree?

Luann answered 10/8, 2014 at 5:47 Comment(0)
R
7

The API docs for ElementTree do not make working with namespaces very clear, but it's mostly straightforward. You need to wrap elements in QName(), and not put xmlns in your namespace argument.

# Deal with confusion between ElementTree module and class name
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ElementTree, Element, SubElement, QName, tostring
from io import BytesIO

# Factored into a constant
GOOG = 'http://base.google.com/ns/1.0'
ET.register_namespace('g', GOOG)

# Make some elements
top = Element('top')
foo = SubElement(top, QName(GOOG, 'foo'))

# This is an alternate, seemingly inferior approach
# Documented here: http://effbot.org/zone/element-qnames.htm
# But not in the Python.org API docs as far as I can tell
bar = SubElement(top, '{http://base.google.com/ns/1.0}bar')

# Now it should output the namespace
print(tostring(top))

# But ElementTree.write() is the one that adds the xml declaration also
output = BytesIO()
ElementTree(top).write(output, xml_declaration=True)
print(output.getvalue())
Ringdove answered 10/8, 2014 at 6:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.