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

如何获取HTML path元素的d属性值并在TextBox中显示

解决HTML中path元素"d"属性值获取并显示到TextBox的问题

看起来你的代码已经能定位到highcharts-series元素,但没能正确取出path的d属性值,我帮你分析下问题并给出修正方案:

问题分析

  1. 变量初始化与作用域问题:你的row变量如果在循环中没找到匹配元素会处于未赋值状态,直接调用GetAttribute可能报错;即使找到,当前代码只取第一个匹配元素的第一个子元素,若子元素顺序不符合预期(或者你需要多个path的d值),就会出现无内容的情况。
  2. 元素定位不够精准:你直接取col2[0],但没有验证这个子元素是不是path标签,万一有其他子元素就会出错。

修正方案(C#代码)

方案1:精准遍历path元素并获取属性

这个方案会遍历所有highcharts-series下的path元素,把每个的d属性值都添加到TextBox中:

// 先清空TextBox原有内容,避免重复追加
textBox1.Text = string.Empty;

foreach(HtmlElement elm in col) {
    if (elm.GetAttribute("className") == "highcharts-series") {
        // 遍历当前series下的所有子元素,筛选出path标签
        foreach(HtmlElement childElm in elm.Children) {
            if (childElm.TagName.Equals("path", StringComparison.OrdinalIgnoreCase)) {
                string dValue = childElm.GetAttribute("d");
                if (!string.IsNullOrEmpty(dValue)) {
                    // 每个d值换行显示,方便查看
                    textBox1.Text += dValue + Environment.NewLine;
                }
            }
        }
    }
}

方案2:用JS脚本直接获取(更适合SVG元素)

如果WebBrowser控件对SVG元素的属性支持有限,用JS脚本获取会更可靠:

// 获取第一个path的d值
string firstDValue = webBrowser1.Document.InvokeScript("eval", 
    new object[] { "document.querySelector('.highcharts-series path').getAttribute('d')" }) as string;

if (!string.IsNullOrEmpty(firstDValue)) {
    textBox1.Text = firstDValue;
}

// 如果需要获取所有path的d值,用这段代码
// string allDValues = webBrowser1.Document.InvokeScript("eval", 
//     new object[] { "Array.from(document.querySelectorAll('.highcharts-series path')).map(p => p.getAttribute('d')).join('\\n')" }) as string;
// textBox1.Text = allDValues ?? string.Empty;

关键注意点

  • 确保你的col集合确实包含了目标highcharts-series元素,可以在循环中加断点验证。
  • 对于SVG元素,部分属性用HtmlElement.GetAttribute可能无法正确读取,这时候JS脚本的方式是更稳妥的选择。

内容的提问来源于stack exchange,提问作者Reza Sh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:05:27