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

如何在Python 3中读取XML根节点下元素的属性值?

获取TouchXPRT XML中WorkLoad元素的Duration属性值

先明确你要解析的XML结构示例:

return (<WorkLoad Name="SampleTask" Duration="4567" />
)

和你之前处理标签内容的场景不同,属性值存在元素的属性节点里,而非标签对之间的文本。下面是几种常用编程语言的实现方案:

Python(用xml.etree.ElementTree)

import xml.etree.ElementTree as ET

# 加载目标XML文件
tree = ET.parse('touchxprt_results.xml')
root = tree.getroot()

# 定位所有WorkLoad元素,提取Duration属性
for workload in root.findall('.//WorkLoad'):
    duration = workload.get('Duration')
    if duration:
        print(f"任务耗时: {duration}")

用get()方法直接指定属性名就能拿到值,比取标签内容的text属性更直接。

C#(用Linq to XML)

using System;
using System.Linq;
using System.Xml.Linq;

class TouchXprtParser
{
    static void Main()
    {
        XDocument resultDoc = XDocument.Load("touchxprt_results.xml");
        
        // 查询所有WorkLoad节点,提取Duration属性值
        var durationList = resultDoc.Descendants("WorkLoad")
                                    .Select(node => node.Attribute("Duration")?.Value);
        
        foreach (var duration in durationList)
        {
            if (!string.IsNullOrEmpty(duration))
            {
                Console.WriteLine($"任务耗时: {duration}");
            }
        }
    }
}

通过Attribute("Duration")获取属性节点,再取Value得到具体值,?.是为了避免属性不存在时抛出空引用异常。

PowerShell

# 读取XML文件内容
$xmlContent = [xml](Get-Content -Path "touchxprt_results.xml")

# 遍历所有WorkLoad节点
foreach ($workload in $xmlContent.SelectNodes("//WorkLoad")) {
    # 直接通过属性名访问
    if ($workload.Duration) {
        Write-Host "任务耗时: $($workload.Duration)"
    }
}

PowerShell对XML的属性支持直接访问,语法更简洁。

核心逻辑总结:别再用获取标签文本的方式(比如Python的.text),而是调用解析库对应的属性获取方法,直接指定Duration属性名即可拿到值。

内容的提问来源于stack exchange,提问作者Ronny Valtonen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:03:29