最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python生成xml文件方法示例

 更新時(shí)間:2023年09月01日 11:38:30   作者:小小平不平凡  
Python標(biāo)準(zhǔn)庫(kù)xml.etree.ElementTree提供了一些生成XML的工具,可以用于創(chuàng)建和操作XML文檔,本文就來(lái)介紹以下如何生成生成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():訪問(wèn)標(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腳本模版文件。通過(guò)對(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')
  • 通過(guò)索引解析元素并賦值
    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)文章

  • pycharm如何調(diào)整最大堆發(fā)揮最大

    pycharm如何調(diào)整最大堆發(fā)揮最大

    本文詳細(xì)介紹了如何在PyCharmar中設(shè)置最大堆內(nèi)存以提高Python程序運(yùn)行效率,建議將8GB內(nèi)存設(shè)置為約6GB,利用約75%的內(nèi)存運(yùn)行效果最佳
    2026-05-05
  • Python實(shí)現(xiàn)接口下載json文件并指定文件名稱

    Python實(shí)現(xiàn)接口下載json文件并指定文件名稱

    在 Web 開發(fā)中,提供文件下載功能是一種常見的需求,尤其是當(dāng)涉及到導(dǎo)出數(shù)據(jù)為 JSON 格式時(shí),為了確保文件名的自定義以及避免亂碼問(wèn)題,開發(fā)者需要采取一些特定的措施,本文介紹了Python實(shí)現(xiàn)接口下載json文件并指定文件名稱,需要的朋友可以參考下
    2024-10-10
  • Python中函數(shù)的定義、調(diào)用及作用說(shuō)明

    Python中函數(shù)的定義、調(diào)用及作用說(shuō)明

    Python函數(shù)可通過(guò)def定義,lambda聲明,支持缺省參數(shù)和不定長(zhǎng)參數(shù)(*號(hào),僅一個(gè)且在最后),調(diào)用時(shí)可指定參數(shù)順序,函數(shù)可作為類方法、局部變量或高階函數(shù)參數(shù)/返回值
    2025-07-07
  • Python+SQLAlchemy輕松實(shí)現(xiàn)管理數(shù)據(jù)庫(kù)

    Python+SQLAlchemy輕松實(shí)現(xiàn)管理數(shù)據(jù)庫(kù)

    QLAlchemy是一個(gè)強(qiáng)大的ORM(對(duì)象關(guān)系映射)庫(kù),它允許您通過(guò)Python代碼與關(guān)系型數(shù)據(jù)庫(kù)進(jìn)行交互,本文我們將學(xué)習(xí)如何使用Python和SQLAlchemy庫(kù)來(lái)輕松管理數(shù)據(jù)庫(kù),需要的可以參考下
    2023-05-05
  • python之loc與iloc的用法及說(shuō)明

    python之loc與iloc的用法及說(shuō)明

    這篇文章主要介紹了python之loc與iloc的用法及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-06-06
  • Python中ModuleNotFoundError模塊未找到的解決方法

    Python中ModuleNotFoundError模塊未找到的解決方法

    ModuleNotFoundError是常見的運(yùn)行時(shí)錯(cuò)誤,通常由模塊路徑配置、安裝缺失或命名沖突導(dǎo)致,本文主要介紹了Python中ModuleNotFoundError模塊未找到的解決方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2025-06-06
  • python對(duì)list中的每個(gè)元素進(jìn)行某種操作的方法

    python對(duì)list中的每個(gè)元素進(jìn)行某種操作的方法

    今天小編就為大家分享一篇python對(duì)list中的每個(gè)元素進(jìn)行某種操作的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • python對(duì)批量WAV音頻進(jìn)行等長(zhǎng)分割的方法實(shí)現(xiàn)

    python對(duì)批量WAV音頻進(jìn)行等長(zhǎng)分割的方法實(shí)現(xiàn)

    這篇文章主要介紹了python對(duì)批量WAV音頻進(jìn)行等長(zhǎng)分割的方法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • 分享8?個(gè)常用pandas的?index設(shè)置

    分享8?個(gè)常用pandas的?index設(shè)置

    這篇文章主要介紹了分享8?個(gè)常用pandas的?index設(shè)置,pandas?中的?index?是行索引或行標(biāo)簽。行標(biāo)簽可以說(shuō)是?pandas?的靈魂一簽,支撐了?pandas?很多強(qiáng)大的業(yè)務(wù)功能,比如多個(gè)數(shù)據(jù)框的?join,?merge?操作,自動(dòng)對(duì)齊等,下面來(lái)看看文章得具體介紹吧
    2021-12-12
  • 8個(gè)Python必備的PyCharm插件(附下載地址)

    8個(gè)Python必備的PyCharm插件(附下載地址)

    Python是一種廣泛使用的編程語(yǔ)言,PyCharm是最受歡迎的Python IDE之一,本文就來(lái)介紹一下8個(gè)Python必備的PyCharm插件,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-01-01

最新評(píng)論

龙泉市| 平安县| 临夏市| 兴仁县| 清涧县| 宜兴市| 林芝县| 长沙县| 海丰县| 榆社县| 昆明市| 资溪县| 马关县| 蒙城县| 沅江市| 京山县| 宁国市| 宝丰县| 禹城市| 海门市| 通榆县| 肇东市| 铜山县| 张北县| 镇远县| 上蔡县| 桐城市| 乌什县| 六枝特区| 永德县| 麻江县| 福清市| 杭锦旗| 博乐市| 青川县| 德保县| 枣强县| 仙桃市| 甘肃省| 密云县| 宿迁市|