1 回答

TA貢獻1963條經驗 獲得超6個贊
以下:
import xml.etree.ElementTree as ET
xml = '''<testsuite name="Setup">
<testcase classname="Configuration" name="xxx">
<data>abc_qwe</data>
</testcase>
<testcase classname="Configuration" name="yyy">
<data>xyzzzz</data>
</testcase>
</testsuite>'''
root = ET.fromstring(xml)
test_cases = root.findall('.//testcase')
for test_case in test_cases:
test_case.find('./data').text = test_case.attrib['name']
ET.dump(root)
輸出
<testsuite name="Setup">
<testcase classname="Configuration" name="xxx">
<data>xxx</data>
</testcase>
<testcase classname="Configuration" name="yyy">
<data>yyy</data>
</testcase>
</testsuite>
另一種方式(用數據文本設置name屬性的值)
import xml.etree.ElementTree as ET
xml = '''<testsuite name="Setup">
<testcase classname="Configuration" name="xxx">
<data>data_1</data>
</testcase>
<testcase classname="Configuration" name="yyy">
<data>data_2</data>
</testcase>
</testsuite>'''
root = ET.fromstring(xml)
test_cases = root.findall('.//testcase')
for test_case in test_cases:
test_case.attrib['name'] = test_case.find('./data').text
ET.dump(root)
添加回答
舉報