在Python中将XML片段附加到另一个XML中

2024-09-30 14:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

需要读取CSV文件并使用其中的详细信息需要创建一个XML片段,该片段需要放置在特定区域(节点内)的另一个XML片段中。 第一部分已经完成。需要做第二部分。在这方面需要帮助。结果还需要写入新的XML文件。在

import csv import lxml.etree as ET import xml.etree.cElementTree as ETT from lxml import etree, html csvFile = open('parameters.csv') readCsv = csv.reader(csvFile) data = [] for row in readCsv: data.append(row) csvFile.close() def convert_row(row): return """<hashTree><TransactionController guiclass="TransactionControllerGui" testclass="TransactionController" testname="%s" enabled="true"> <boolProp name="TransactionController.includeTimers">false</boolProp> <boolProp name="TransactionController.parent">false</boolProp> </TransactionController> <hashTree> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Request" enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true"> <collectionProp name="Arguments.arguments" /> </elementProp> <stringProp name="HTTPSampler.domain">"%s" </stringProp> <stringProp name="HTTPSampler.port"> </stringProp> <stringProp name="HTTPSampler.protocol"> </stringProp> <stringProp name="HTTPSampler.contentEncoding"> </stringProp> <stringProp name="HTTPSampler.path">"%s" </stringProp> <stringProp name="HTTPSampler.method">"%s"</stringProp> <boolProp name="HTTPSampler.follow_redirects">true</boolProp> <boolProp name="HTTPSampler.auto_redirects">false</boolProp> <boolProp name="HTTPSampler.use_keepalive">true</boolProp> <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp> <stringProp name="HTTPSampler.embedded_url_re"> </stringProp> <stringProp name="HTTPSampler.connect_timeout"> </stringProp> <stringProp name="HTTPSampler.response_timeout"> </stringProp> </HTTPSamplerProxy> </hashTree> </hashTree>"""%(row[0],row[1],row[2],row[3]) fragment = '\n'.join([convert_row(row) for row in data[1:]]) TF = ET.parse('testXml.xml') content = TF.findall("//jmeterTestPlan/hashTree/hashTree/hashTree/") content.append(fragment) print(content)


Tags: csvcsvfilenameimportfalsetruexmlarguments
1条回答
网友
1楼 · 发布于 2024-09-30 14:30:47

在附加字符串之前,需要将字符串转换为XML。在

fragment = '\n'.join([convert_row(row) for row in data[1:]])
aet=ET.fromstring(fragment)
TF = ET.ElementTree(file='testXml.xml')
for child in TF.xpath('//jmeterTestPlan/hashTree/hashTree[1]'):
child.append(aet)
TF.write('out.jmx')

相关问题 更多 >