218.python 操作xml文件

 


python 操作jmeter脚本获取修改参数

from xml.etree import ElementTree as et
from pathlib import Path

# 比如我想把一段xml插入到一个xml中可以将其内容构建一个新的xml
result_collector = """<?xml version="1.0" encoding="UTF-8"?>
<root>
<ResultCollector guiclass="ViewResultsFullVisualizer" 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/>
</root>"""

file_path = Path("/tmp/HTTP2.jmx")
tree = et.parse(file_path)
root = tree.getroot()

# 自从发现可以使用xpath方式, 这种方式我就放弃了
# for neighbor in root.iter("ThreadGroup"):
#     for child in neighbor:
#         if child.attrib.get()
#         print(child.tag, child.attrib)

# 直接使用xpath, 支持的xpath不全但是不影响使用
thread_name = root.find(".//ThreadGroup").attrib.get("testname")
num_threads = root.find(".//stringProp[@name='ThreadGroup.num_threads']").text
t_test_name = "{}--{}.jmx".format(num_threads, thread_name)
root.find(".//ThreadGroup").set("testname", t_test_name)
ramp_time = root.find(".//stringProp[@name='ThreadGroup.ramp_time']").text
duration = root.find(".//stringProp[@name='ThreadGroup.duration']").text
# 没有xpath的路径选择功能,只能使用or代替
loops = root.find(".//elementProp/intProp[@name='LoopController.loops']") or root.find(".//elementProp/stringProp[@name='LoopController.loops']")
print(type(loops))
# 还可以直接修改改, 不过需要重新写入, 否则默认知识写到内存
loops.text = "998"
apis = root.findall(".//hashTree/JavaSampler") or root.findall(".//hashTree/HTTPSamplerProxy")

for api in apis:
    api_name = api.get("testname")
    elm = api.set("testname", "{}-Jmx-{}".format(api_name, t_test_name))

# pathlib.Path支持重命名, 但是发现还是需要先写入之后才方便重命名
# file_path.rename("/tmp/" + t_test_name)
print(thread_name, num_threads, ramp_time, duration, loops.text)

# 遍历另一个xml, 将其中的element插入root的node的element下
# node = root.find("./hashTree/hashTree/hashTree")
# collector_chart = et.fromstring(result_collector)
# for child in collector_chart:
#     node.append(child)

# 修改之后需要重新保存
# tree.write(file_path)

参考:

xpath学习: https://www.shouce.ren/api/view/a/6968

python xml包: https://docs.python.org/zh-cn/3/library/xml.etree.elementtree.html#modifying-an-xml-file

posted @   楠海  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示

目录导航