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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python使用Geany编辑器配置方法

    python使用Geany编辑器配置方法

    这篇文章主要介绍了python使用Geany编辑器配置方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02
  • python 如何设置守护进程

    python 如何设置守护进程

    这篇文章主要介绍了python 如何设置守护进程,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
    2020-10-10
  • Python排序函数的使用方法详解

    Python排序函数的使用方法详解

    这篇文章主要给大家介绍了关于Python排序函数使用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • Python中异常捕获与处理的方法总结

    Python中异常捕获与处理的方法总结

    Python异常是在程序执行时发生的错误,可能会导致程序终止运行。这篇文章主要为大家总结了Python中异常捕获与处理的方法,需要的可以参考一下
    2023-04-04
  • Python+Tkinter打造签名设计工具

    Python+Tkinter打造签名设计工具

    这篇文章主要为大家分享如何利用Python Tkinter库制作带图形界面的一个签名设计工具,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2022-04-04
  • 更改Python的pip install 默认安装依赖路径方法详解

    更改Python的pip install 默认安装依赖路径方法详解

    今天小编就为大家分享一篇更改Python的pip install 默认安装依赖路径方法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • Pytorch中的gather使用方法

    Pytorch中的gather使用方法

    这篇文章主要介绍了Pytorch中的gather使用方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-05-05
  • pyinstaller打包可执行程序过程中的常见错误解决

    pyinstaller打包可执行程序过程中的常见错误解决

    这篇文章主要介绍了pyinstaller打包可执行程序过程中的常见错误解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • 基于Django filter中用contains和icontains的区别(详解)

    基于Django filter中用contains和icontains的区别(详解)

    下面小编就为大家分享一篇基于Django filter中用contains和icontains的区别,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • python3 图片referer防盗链的实现方法

    python3 图片referer防盗链的实现方法

    本篇文章主要介绍了python3 图片referer防盗链的实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-03-03

最新评论