简体   繁体   中英

Python xml.etree.ElementTree Problems

NEVER MIND - I FOUND MY REAL ISSUE, IT WAS FURTHER ON IN MY CODE THAT I REALIZED.

I am having problems getting xml.etree.ElementTree to work like I expect it to.

xmlData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><suggestedmatches><destination><sortOrder>1</sortOrder><destinationType>destinationType1</destinationType></destination><destination><sortOrder>2</sortOrder><destinationType>destinationType2</destinationType></destination></suggestedmatches>"
root = ET.fromstring(xmlData)
logging.debug("DIAG: %s: root.tag = %s"
  % (FUNCTION_NAME, root.tag))
logging.debug("DIAG: %s: root = %r" % (FUNCTION_NAME, ET.tostring(root)))
destinations = root.findall("destination")
logging.debug('DIAG: %s: destinations = %r' % (FUNCTION_NAME, ET.tostring(destinations)))

I'm trying to figure out why I can't find destinations in root .

DEBUG:root:DIAG: findDestinations(): root.tag = suggestedmatches
DEBUG:root:DIAG: findDestinations(): root = b'<suggestedmatches><destination><sortOrder>1</sortOrder><destinationType>destinationType1</destinationType></destination><destination><sortOrder>2</sortOrder><destinationType>destinationType2</destinationType></destination></suggestedmatches>'
ERROR:root:findDestinations(): Encountered exception on root.findall() - 'list' object has no attribute 'iter'

And if I add the following code after I get root , I am seeing each of the destinations listed in the log:

for destination in root:
  destinationList.append(destination)
  logging.debug('DIAG: %s: destination.tag = %s'
    % (FUNCTION_NAME, destination.tag))

This same code is working in a different script, so I'm not sure why it's not working here.

You are getting None because ET.dump writes to sys.stdout and you are logging return of dump which is None .

From docs :

xml.etree.ElementTree.dump(elem)

Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.

The exact output format is implementation dependent. In this version, it's written as an ordinary XML file.

elem is an element tree or an individual element.

Try using tostring method instead of dump .

logging.debug("DIAG: %s: root = %r" % (FUNCTION_NAME, ET.tostring(root)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM