Python生成xml文件方法示例

 更新时间:2023年09月01日 11:38:30   作者:小小平不平凡  
Python标准库xml.etree.ElementTree提供了一些生成XML的工具,可以用于创建和操作XML文档,本文就来介绍以下如何生成生成xml文件,感兴趣的可以了解一下

一、背景介绍

由于工作中有个需求是需要生成一个jmeter脚本,而jmeter脚本其实就是一个xml文件。因此我只需要掌握如何生存一个xml文件即可

二、基本介绍

  • ElementTree:表示整个XML文件
  • Element:表示树中的一个元素,每个元素都有对应的标签tag
  • text:获取标签内容
  • attrib:获取标签的属性和属性值,是json结构
  • Element.get():访问标签的属性值
  • Element.set():添加和修改标签的属性和属性值
  • Element.append():添加孩子节点
  • Element.remove():删除元素
  • Element.find() :根据标签或路径查找出第一个匹配的元素
  • Element.findall():根据标签或路径查找出所有匹配的子元素

三、示例代码

1、首先提供一个最基本的jmeter脚本模版文件。通过对该模版文件进行修改获得符合要求的jmeter压测脚本

<?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 数据文件设置" 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 请求" 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 请求" 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="察看结果树" 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="聚合报告" 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)

代码解析:

  • 导入包 import xml.etree.ElementTree as ET
  • 使用解析器解析根元素
    # 加载XML树
    tree = ET.parse(template_file_path)
    root = tree.getroot()
  • 根据标签名或路径找到第一个匹配的元素
    root.find('hashTree')
  • 通过索引解析元素并赋值
    csvDataSetElement[2].text = pressdata_file_path
  • 修改标签的属性值
    child.set("testname", name)
  • 添加新节点元素
     new_elementProp.append(new_stringProp_value)
  • 删除某一个标签
    hashTreeElement.remove(hashTreeElement[8])
  • 创建一个新的元素
    new_stringProp_value = ET.Element('stringProp')

 到此这篇关于Python生成xml文件方法示例的文章就介绍到这了,更多相关Python生成xml内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • pycharm如何调整最大堆发挥最大

    pycharm如何调整最大堆发挥最大

    本文详细介绍了如何在PyCharmar中设置最大堆内存以提高Python程序运行效率,建议将8GB内存设置为约6GB,利用约75%的内存运行效果最佳
    2026-05-05
  • Python实现接口下载json文件并指定文件名称

    Python实现接口下载json文件并指定文件名称

    在 Web 开发中,提供文件下载功能是一种常见的需求,尤其是当涉及到导出数据为 JSON 格式时,为了确保文件名的自定义以及避免乱码问题,开发者需要采取一些特定的措施,本文介绍了Python实现接口下载json文件并指定文件名称,需要的朋友可以参考下
    2024-10-10
  • Python中函数的定义、调用及作用说明

    Python中函数的定义、调用及作用说明

    Python函数可通过def定义,lambda声明,支持缺省参数和不定长参数(*号,仅一个且在最后),调用时可指定参数顺序,函数可作为类方法、局部变量或高阶函数参数/返回值
    2025-07-07
  • Python+SQLAlchemy轻松实现管理数据库

    Python+SQLAlchemy轻松实现管理数据库

    QLAlchemy是一个强大的ORM(对象关系映射)库,它允许您通过Python代码与关系型数据库进行交互,本文我们将学习如何使用Python和SQLAlchemy库来轻松管理数据库,需要的可以参考下
    2023-05-05
  • python之loc与iloc的用法及说明

    python之loc与iloc的用法及说明

    这篇文章主要介绍了python之loc与iloc的用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-06-06
  • Python中ModuleNotFoundError模块未找到的解决方法

    Python中ModuleNotFoundError模块未找到的解决方法

    ModuleNotFoundError是常见的运行时错误,通常由模块路径配置、安装缺失或命名冲突导致,本文主要介绍了Python中ModuleNotFoundError模块未找到的解决方法,具有一定的参考价值,感兴趣的可以了解一下
    2025-06-06
  • python对list中的每个元素进行某种操作的方法

    python对list中的每个元素进行某种操作的方法

    今天小编就为大家分享一篇python对list中的每个元素进行某种操作的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-06-06
  • python对批量WAV音频进行等长分割的方法实现

    python对批量WAV音频进行等长分割的方法实现

    这篇文章主要介绍了python对批量WAV音频进行等长分割的方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • 分享8 个常用pandas的 index设置

    分享8 个常用pandas的 index设置

    这篇文章主要介绍了分享8 个常用pandas的 index设置,pandas 中的 index 是行索引或行标签。行标签可以说是 pandas 的灵魂一签,支撑了 pandas 很多强大的业务功能,比如多个数据框的 join, merge 操作,自动对齐等,下面来看看文章得具体介绍吧
    2021-12-12
  • 8个Python必备的PyCharm插件(附下载地址)

    8个Python必备的PyCharm插件(附下载地址)

    Python是一种广泛使用的编程语言,PyCharm是最受欢迎的Python IDE之一,本文就来介绍一下8个Python必备的PyCharm插件,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01

最新评论