Aditya
Aditya

Reputation: 3158

How to add python keyword terms as tag attributes in lxml?

I'm using lxml to build an XML based on some data.

    root = etree.Element('sentences')
for item in aspectSentenceList:
    print item
    sentenceTag = etree.SubElement(root, "sentence", id=item[0])
    textTag = etree.SubElement(sentenceTag, "text", text=item[1])
    aspectTermsTag = etree.SubElement(sentenceTag, "aspectTerms")
    for asp in item[2]:
        aspectTermTag = etree.SubElement(aspectTermsTag, "aspectTerm", term = asp[0], frm = asp[1], to = asp[2])

The catch is in last line. There are three attributes, term, from and to. The issue is, python wouldn't let me use "from" keyword for any tasks other than usual imports. Though I have done temporary workaround by using frm instead of from, and replace all such strings later. However how can I do this without trustless hacks?

Upvotes: 2

Views: 313

Answers (1)

Aditya
Aditya

Reputation: 3158

Oh got it just within five minutes after posting the question. The documentation mentions that attributes are python dictionaries. I updated the last line with:-

aspectTermTag = etree.SubElement(aspectTermsTag, "aspectTerm", {"term":asp[0], "from": asp[1], "to":asp[2]})

Upvotes: 1

Related Questions