在Python的另一个XML中附加XML片段



需要读取一个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)

您需要在附加之前将字符串转换为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')

最新更新