Possible Duplicate:
Parsing blank XML tags with LXML and Python
Given the following XML file:
<Car>
<Color>Blue</Color>
<Make>Chevy</Make>
<Model/>
</Car>
and using the following code:
Car = element.xpath('//Root/Foo/Bar/Car/node()')
parsedCarData = [{field.tag: field.text for field in Car} for action in Car]
How can I replace key values of type None with a blank string so I can use parsed key values into a MySQL statement.
My Attempt – Thanks to Marcin
Using a turnary seemed to work
parsedCars = [{field.tag: field.text if isinstance(field.text,str) else '' for field in Cars} for action in Cars]
For my cases it has always evaluated as true.However when outputting a previous None type is outputs twice. Improvements are welcome!
Given your requirement, you might be better off filtering on
is None, but in practice, I doubt this will make a difference:You should probably use
basestrinstead ofstr, though, because your code will replace all instances ofunicodewith'', should lxml ever switch to unicode.