You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python解析XML时,找到目标行后如何抓取其下第二行内容?

解决XML匹配目标行后提取下两行内容的问题

针对你的需求,直接修改现有代码,利用文件迭代器的next()方法在找到目标行后直接读取后续指定行即可,无需重新全量匹配重复标签:

修改后的代码

import re

with open(filepath) as f:
    lines_iter = iter(f)
    for line in lines_iter:
        if pattern.search(line):
            # 提取主机名并输出
            host_match = re.findall('"([^"]*)"', line)
            if host_match:
                print(host_match[0])
            # 向下跳过1行,读取第2行内容
            try:
                next(lines_iter)  # 跳过<Description>所在行
                target_line = next(lines_iter)  # 获取<DescriptionValue>所在行
                # 提取value属性值
                desc_match = re.findall('value=&quot;([^&quot;]*)&quot;', target_line)
                if desc_match:
                    print(desc_match[0])
            except StopIteration:
                # 处理文件末尾无足够行的情况
                pass

代码说明

  1. 将文件对象转为迭代器lines_iter,灵活控制后续行的读取,不打乱原有遍历逻辑
  2. 匹配到目标行后,先提取并输出主机名
  3. 用next(lines_iter)跳过中间的<Description>行,再通过一次next()获取目标的<DescriptionValue>行
  4. 对目标行提取value属性值并输出,同时用try-except处理文件末尾没有足够行的异常
  5. 避免了全量匹配<DescriptionValue>标签导致的误匹配,只处理当前主机名对应的后续行

内容的提问来源于stack exchange,提问作者Amr Mashrah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:50:21