简体   繁体   中英

ValueError on writing lxml text

I have the following block to write an xml tag. Sometimes the name is already in the correct form (that is, it won't error), and sometimes it is not

if 'Name' in title_data:
    name = etree.SubElement(info, 'Name')
    try:
        name.text = title_data['Name']
    except ValueError:
        name.text = title_data['Name'].decode('utf-8')

Is there a way to simplify this? For example, something along the lines of:

name.text = title_data['Name'] if (**something**) else title_data['Name'].decode('utf-8')

I assume that you want to avoid having to write similar code for every element you want to set. This has the smell of trying to treat the symptom rather than the cause, but if nothing else, you can simply break that out into a helper function:

def assign_text(field, text):
    try:
        field.text = text
    except ValueError:
        field.text = text.decode("utf-8")

# ...
if "Name" in title_data:
    name = etree.SubElement(info, "Name")
    assign_text(name, title_data["Name"] or None)

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