It has great sushi and even better s...">

XML ElementTree - Indexing Tags

I have an XML file:

<sentence id="en_BlueRibbonSushi_478218345:2">
   <text>It has great sushi and even better service.</text>
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:3">
   <text>The entire staff was extremely accomodating and tended to my every need.</text>
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:4">
   <text>I&apos;ve been to this restaurant over a dozen times with no complaints to date.</text>
</sentence>

Using XML ElementTree, I would like to insert a tag <Opinion>that has an attribute category=. Let's say I have a list of characters list = ['a', 'b', 'c'], is it possible to incrementally assign them to each text so that I have:

<sentence id="en_BlueRibbonSushi_478218345:2">
   <text>It has great sushi and even better service.</text>
   <Opinion category='a' />
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:3">
   <text>The entire staff was extremely accomodating and tended to my every need.</text>
   <Opinion category='b' />
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:4">
   <text>I&apos;ve been to this restaurant over a dozen times with no complaints to date.</text>
   <Opinion category='c' />
</sentence>

I know that I can use the id attribute of a proposal, but this will require a major restructuring of my code. Basically, I would like to be able to index each sentence entry to align with my list index.

+6
source share
1 answer

SubElement factory . , XML data, :

import xml.etree.ElementTree as ET
tree = ET.XML(data)
for elem, category in zip(tree.findall('sentence'), ['a', 'b', 'c']):
    Opinion  = ET.SubElement(elem, 'Opinion')
    Opinion.set('category', category)

ET.dump(tree)  # prints the tree; tree.write('output.xml') is another option
+4

Source: https://habr.com/ru/post/1016141/


All Articles