Python生成xml文件方法示例
一、背景介紹
由于工作中有個(gè)需求是需要生成一個(gè)jmeter腳本,而jmeter腳本其實(shí)就是一個(gè)xml文件。因此我只需要掌握如何生存一個(gè)xml文件即可
二、基本介紹
- ElementTree:表示整個(gè)XML文件
- Element:表示樹中的一個(gè)元素,每個(gè)元素都有對(duì)應(yīng)的標(biāo)簽tag
- text:獲取標(biāo)簽內(nèi)容
- attrib:獲取標(biāo)簽的屬性和屬性值,是json結(jié)構(gòu)
- Element.get():訪問標(biāo)簽的屬性值
- Element.set():添加和修改標(biāo)簽的屬性和屬性值
- Element.append():添加孩子節(jié)點(diǎn)
- Element.remove():刪除元素
- Element.find() :根據(jù)標(biāo)簽或路徑查找出第一個(gè)匹配的元素
- Element.findall():根據(jù)標(biāo)簽或路徑查找出所有匹配的子元素
三、示例代碼
1、首先提供一個(gè)最基本的jmeter腳本模版文件。通過對(duì)該模版文件進(jìn)行修改獲得符合要求的jmeter壓測(cè)腳本
<?xml version="1.0" encoding="UTF-8"?> <jmeterTestPlan version="1.2" properties="5.0" jmeter="5.4.1"> <hashTree> <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="template" enabled="true"> <stringProp name="TestPlan.comments"></stringProp> <boolProp name="TestPlan.functional_mode">false</boolProp> <boolProp name="TestPlan.tearDown_on_shutdown">true</boolProp> <boolProp name="TestPlan.serialize_threadgroups">false</boolProp> <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true"> <collectionProp name="Arguments.arguments"/> </elementProp> <stringProp name="TestPlan.user_define_classpath"></stringProp> </TestPlan> <hashTree> <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true"> <stringProp name="ThreadGroup.on_sample_error">continue</stringProp> <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true"> <boolProp name="LoopController.continue_forever">false</boolProp> <intProp name="LoopController.loops">-1</intProp> </elementProp> <stringProp name="ThreadGroup.num_threads">1</stringProp> <stringProp name="ThreadGroup.ramp_time"></stringProp> <boolProp name="ThreadGroup.scheduler">true</boolProp> <stringProp name="ThreadGroup.duration">1</stringProp> <stringProp name="ThreadGroup.delay"></stringProp> <boolProp name="ThreadGroup.same_user_on_next_iteration">false</boolProp> </ThreadGroup> <hashTree> <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="CSV 數(shù)據(jù)文件設(shè)置" enabled="true"> <stringProp name="delimiter">\t</stringProp> <stringProp name="fileEncoding">UTF-8</stringProp> <stringProp name="filename">press.txt</stringProp> <boolProp name="ignoreFirstLine">false</boolProp> <boolProp name="quotedData">false</boolProp> <boolProp name="recycle">false</boolProp> <stringProp name="shareMode">shareMode.all</stringProp> <boolProp name="stopThread">true</boolProp> <stringProp name="variableNames">uri,header,body</stringProp> </CSVDataSet> <hashTree/> <Arguments guiclass="ArgumentsPanel" testclass="Arguments" testname="用戶定義的變量" enabled="true"> <collectionProp name="Arguments.arguments"> <elementProp name="ip" elementType="Argument"> <stringProp name="Argument.name">ip</stringProp> <stringProp name="Argument.value"></stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> <elementProp name="port" elementType="Argument"> <stringProp name="Argument.name">port</stringProp> <stringProp name="Argument.value"></stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> </collectionProp> </Arguments> <hashTree/> <HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="HTTP信息頭管理器" enabled="true"> <collectionProp name="HeaderManager.headers"/> </HeaderManager> <hashTree/> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP GET 請(qǐng)求" enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="用戶定義的變量" enabled="true"> <collectionProp name="Arguments.arguments"/> </elementProp> <stringProp name="HTTPSampler.domain">${ip}</stringProp> <stringProp name="HTTPSampler.port">${port}</stringProp> <stringProp name="HTTPSampler.protocol">http</stringProp> <stringProp name="HTTPSampler.contentEncoding">utf-8</stringProp> <stringProp name="HTTPSampler.path">${uri}</stringProp> <stringProp name="HTTPSampler.method">GET</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/> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP POST 請(qǐng)求" enabled="true"> <boolProp name="HTTPSampler.postBodyRaw">true</boolProp> <elementProp name="HTTPsampler.Arguments" elementType="Arguments"> <collectionProp name="Arguments.arguments"> <elementProp name="" elementType="HTTPArgument"> <boolProp name="HTTPArgument.always_encode">false</boolProp> <stringProp name="Argument.value">${body}</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> </collectionProp> </elementProp> <stringProp name="HTTPSampler.domain">${ip}</stringProp> <stringProp name="HTTPSampler.port">${port}</stringProp> <stringProp name="HTTPSampler.protocol">http</stringProp> <stringProp name="HTTPSampler.contentEncoding">utf-8</stringProp> <stringProp name="HTTPSampler.path">${uri}</stringProp> <stringProp name="HTTPSampler.method">POST</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/> <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="察看結(jié)果樹" enabled="true"> <boolProp name="ResultCollector.error_logging">true</boolProp> <objProp> <name>saveConfig</name> <value class="SampleSaveConfiguration"> <time>true</time> <latency>true</latency> <timestamp>true</timestamp> <success>true</success> <label>true</label> <code>true</code> <message>true</message> <threadName>true</threadName> <dataType>true</dataType> <encoding>false</encoding> <assertions>true</assertions> <subresults>true</subresults> <responseData>false</responseData> <samplerData>false</samplerData> <xml>false</xml> <fieldNames>true</fieldNames> <responseHeaders>false</responseHeaders> <requestHeaders>false</requestHeaders> <responseDataOnError>false</responseDataOnError> <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage> <assertionsResultsToSave>0</assertionsResultsToSave> <bytes>true</bytes> <sentBytes>true</sentBytes> <url>true</url> <threadCounts>true</threadCounts> <idleTime>true</idleTime> <connectTime>true</connectTime> </value> </objProp> <stringProp name="filename"></stringProp> </ResultCollector> <hashTree/> <ResultCollector guiclass="StatVisualizer" testclass="ResultCollector" testname="聚合報(bào)告" enabled="true"> <boolProp name="ResultCollector.error_logging">false</boolProp> <objProp> <name>saveConfig</name> <value class="SampleSaveConfiguration"> <time>true</time> <latency>true</latency> <timestamp>true</timestamp> <success>true</success> <label>true</label> <code>true</code> <message>true</message> <threadName>true</threadName> <dataType>true</dataType> <encoding>false</encoding> <assertions>true</assertions> <subresults>true</subresults> <responseData>false</responseData> <samplerData>false</samplerData> <xml>false</xml> <fieldNames>true</fieldNames> <responseHeaders>false</responseHeaders> <requestHeaders>false</requestHeaders> <responseDataOnError>false</responseDataOnError> <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage> <assertionsResultsToSave>0</assertionsResultsToSave> <bytes>true</bytes> <sentBytes>true</sentBytes> <url>true</url> <threadCounts>true</threadCounts> <idleTime>true</idleTime> <connectTime>true</connectTime> </value> </objProp> <stringProp name="filename"></stringProp> </ResultCollector> <hashTree/> </hashTree> </hashTree> </hashTree> </jmeterTestPlan>
2、修改xml文件的python代碼
tree = ET.parse(template_path) root = tree.getroot() for child in root.find('hashTree'): print("curr child tag", child.tag) if child.tag == "hashTree": hashTreeElement = child.find('hashTree') csvDataSetElement = hashTreeElement[0] csvDataSetElement[2].text = pressdata_file_path collectionProp = hashTreeElement[2][0] collectionProp[0][1].text = ip collectionProp[1][1].text = port collectionProp_of_header = hashTreeElement[4][0] for key in header.keys(): new_elementProp = ET.Element('elementProp') new_elementProp.attrib = {"name":"", "elementType":"Header"} new_stringProp_name = ET.Element('stringProp') new_stringProp_name.text = key new_stringProp_name.attrib = {"name":"Header.name"} new_stringProp_value = ET.Element('stringProp') new_stringProp_value.text = header[key] new_stringProp_value.attrib = {"name":"Header.value"} new_elementProp.append(new_stringProp_name) new_elementProp.append(new_stringProp_value) collectionProp_of_header.append(new_elementProp) if method == "get": hashTreeElement.remove(hashTreeElement[8]) hashTreeElement.remove(hashTreeElement[8]) elif method == "post": hashTreeElement.remove(hashTreeElement[6]) hashTreeElement.remove(hashTreeElement[6]) if child.tag == "TestPlan": child.set("testname", name)
代碼解析:
- 導(dǎo)入包 import xml.etree.ElementTree as ET
- 使用解析器解析根元素
# 加載XML樹 tree = ET.parse(template_file_path) root = tree.getroot()
- 根據(jù)標(biāo)簽名或路徑找到第一個(gè)匹配的元素
root.find('hashTree')
- 通過索引解析元素并賦值
csvDataSetElement[2].text = pressdata_file_path
- 修改標(biāo)簽的屬性值
child.set("testname", name)
- 添加新節(jié)點(diǎn)元素
new_elementProp.append(new_stringProp_value)
- 刪除某一個(gè)標(biāo)簽
hashTreeElement.remove(hashTreeElement[8])
- 創(chuàng)建一個(gè)新的元素
new_stringProp_value = ET.Element('stringProp')
到此這篇關(guān)于Python生成xml文件方法示例的文章就介紹到這了,更多相關(guān)Python生成xml內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 實(shí)現(xiàn)圖像逐像素點(diǎn)取鄰域數(shù)據(jù)
這篇文章主要介紹了Python 實(shí)現(xiàn)圖像逐像素點(diǎn)取鄰域數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03Python網(wǎng)絡(luò)爬蟲之獲取網(wǎng)絡(luò)數(shù)據(jù)
本文介紹了Python中用于獲取網(wǎng)絡(luò)數(shù)據(jù)的重要工具之一——Requests庫,詳細(xì)講解了Requests庫的基本使用方法、請(qǐng)求方法、請(qǐng)求頭、請(qǐng)求參數(shù)、Cookies、Session等內(nèi)容,并結(jié)合實(shí)例代碼展示了Requests庫的應(yīng)用場(chǎng)景2023-04-04在Windows8上的搭建Python和Django環(huán)境
作為一個(gè).NET程序員,真心不喜歡以及PHP這種松散的語法。有人說,程序員應(yīng)該多學(xué)幾門語言,本想學(xué)習(xí)Java,無奈感覺Java的語法太啰嗦了。很多人都推薦Python,說它的語法簡(jiǎn)潔,執(zhí)行效率高。趁這兩天空閑,開始學(xué)習(xí)Python。2014-07-07利用Python提取PDF文本的簡(jiǎn)單方法實(shí)例
日常工作中我們經(jīng)常會(huì)用到pdf格式的文件,大多數(shù)情況下是瀏覽或者編輯pdf信息,但有時(shí)候需要提取pdf中的文本,下面這篇文章主要給大家介紹了關(guān)于利用Python提取PDF文本的簡(jiǎn)單方法,需要的朋友可以參考下2022-07-07python 實(shí)現(xiàn)讀取csv數(shù)據(jù),分類求和 再寫進(jìn) csv
這篇文章主要介紹了python 實(shí)現(xiàn)讀取csv數(shù)據(jù),分類求和 再寫進(jìn) csv,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05解決python gdal投影坐標(biāo)系轉(zhuǎn)換的問題
今天小編就為大家分享一篇解決python gdal投影坐標(biāo)系轉(zhuǎn)換的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01