Skip to content
Advertisement

XML parsing in python issue using elementTree

I need to parse a soap response and convert to a text file. I am trying to parse the values as detailed below. I am using ElementTree in python

I have the below xml response which I need to parse

JavaScript

I need to use the below code snippet.

JavaScript

The issue is that The below code is not able to find the ‘vendorExtensions”‘. Please help here.

JavaScript

Have tried the below as well

JavaScript

Advertisement

Answer

Your document declares a default namespace of alu.v1:

JavaScript

Any attribute without an explicit namespace is in the alu.v1 namespace. You need to qualify your attribute name appropriately:

JavaScript

While the above is a real problem with your code that needs to be corrected (the Wikipedia entry on XML namespaces may be useful reading if you’re unfamiliar with how namespaces work), there are also some logic problems with your code.

Let’s drop the big list of conditionals from the code and see if it’s actually doing what we think it’s doing. If we run this:

JavaScript

Then using your sample data (once it has been corrected to be syntactically valid), we see as output:

JavaScript

Your search for the {alu.v1}vendorExtensions element will never succeed before the thing on which you’re trying to search (the device variable) is the thing you’re trying to find.

Additionally, the conditional in your loop…

JavaScript

…will never match (there is no element in the entire document for which tag.split("}")[1] == "me" is True).

I’m not entirely clear what you’re trying to do, but here’s are some thoughts:

  • Given your example data, you probably don’t want that for device in inventoryObject: loop
  • We can drastically simplify your code by replacing that long block of conditionals with a list of attributes in which we are interested and then a for loop to extract them.
  • Rather than assigning a bunch of individual variables, we can build up a dictionary with the data from the queryObject

That might look like:

JavaScript

Given your example data, this outputs:

JavaScript

An alternate approach, in which we just transform each queryObject into a dictionary, might look like this:

JavaScript

This will output:

JavaScript

That may or may not be appropriate depending on the structure of your real data and exactly what you’re trying to accomplish.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement