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"?>


          false
          
            saveConfig
            
              
              true
              true
              true
              
              true
              true
              true
              true
              false
              true
              true
              false
              false
              false
              true
              false
              false
              false
              true
              0
              true
              true
              true
              true
              true
              true
            
          
          
        
        
"""

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