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

如何使用C#的XPath根据标签选择表格单元格获取Available QTY值

Grab "Available QTY" Value with XPath in C#

Hey there! Let's get that 10.000 value sorted out. Since you didn't share the full HTML code, I'll cover the most common structures for this kind of label-value pair and give you working XPath expressions + C# code to make it happen.

First, Common HTML Structures & Corresponding XPath

Let's start with two typical scenarios you might be dealing with:

Scenario 1: Table-Based Layout

If your HTML looks something like this:

Available QTY 10.000

Use this XPath to target the sibling <td> right after the "Available QTY" label:

//td[normalize-space(text())='Available QTY']/following-sibling::td[1]/text()

The normalize-space() fixes issues where the label might have extra spaces, tabs, or newlines around it.

Scenario 2: Div/Label-Value Pairs

If your HTML uses divs and spans instead:

Available QTY 10.000

Adjust the XPath to target the sibling span with the value:

//span[normalize-space(text())='Available QTY']/following-sibling::span[@class='value']/text()

C# Implementation (Using HtmlAgilityPack)

.NET's built-in XML parsers can struggle with messy HTML, so HtmlAgilityPack is the go-to library for this. Here's a complete example:

using HtmlAgilityPack;

public string GetAvailableQty(string htmlContent)
{
    var htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(htmlContent);
    
    // Pick the XPath that matches your HTML structure
    string xpath = "//td[normalize-space(text())='Available QTY']/following-sibling::td[1]/text()";
    // Alternative for div/span: string xpath = "//span[normalize-space(text())='Available QTY']/following-sibling::span[@class='value']/text()";
    
    var qtyNode = htmlDoc.DocumentNode.SelectSingleNode(xpath);
    
    if (qtyNode != null)
    {
        // Trim any extra whitespace from the value
        string cleanValue = qtyNode.InnerText.Trim();
        // Optional: Convert to a numeric type if needed
        if (decimal.TryParse(cleanValue, out decimal qtyDecimal))
        {
            return qtyDecimal.ToString("N3"); // Format back to 10.000 if needed
        }
        return cleanValue;
    }
    
    return "Value not found";
}

Troubleshooting Tips

  • If your XPath isn't working, check for:
    • Extra whitespace in the label text (that's why normalize-space() is so useful)
    • Nested elements inside the label (e.g., <td><b>Available QTY</b></td> — adjust the XPath to //td[normalize-space()='Available QTY']/following-sibling::td[1]/text() instead of targeting text())
    • Incorrect sibling indexing (make sure you're using [1] to get the first sibling after the label)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:16:08