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

如何用XPath 1.0匹配包含指定FSA的邮政编码范围row元素?

如何用XPath 1.0查询包含目标FSA的XML 元素

要实现你需要的范围匹配,XPath 1.0支持按字典序的字符串比较,逻辑和你给出的SQL完全一致,但需要注意字符串必须用引号包裹(单引号或双引号都可以)。

正确的XPath表达式

以搜索FSA为L3R为例,正确的XPath应该是:

//row[@postalmin <= 'L3R' and @postalmax >= 'L3R']

你之前的错误原因

你写的//row[@postalmin <= L3R]没有给L3R加引号,XPath会把L3R解析为节点名称而非字符串,自然无法匹配到目标属性值。

C# .NET 代码示例

结合你的开发场景,这里给出用XmlDocument实现查询的代码:

using System.Xml;

public static string FindZoneByFsa(string xmlData, string targetFsa)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xmlData);

    // 转义单引号避免XPath语法错误
    string safeTargetFsa = targetFsa.Replace("'", "''");
    string xpathQuery = $"//row[@postalmin <= '{safeTargetFsa}' and @postalmax >= '{safeTargetFsa}']";

    XmlNode matchedRow = doc.SelectSingleNode(xpathQuery);
    return matchedRow?.Attributes["zone"]?.Value;
}

调用示例:

string xml = @"<xml>
    <row note='Matches L3R' postalmin='L3P' postalmax='L3T' zone='ZONE 11'/>
    <row note='Matches G1J' postalmin='G1A' postalmax='G3K' zone='ZONE 10'/>
</xml>";

// 查询L3R,返回ZONE 11
string zone1 = FindZoneByFsa(xml, "L3R");
// 查询G1J,返回ZONE 10
string zone2 = FindZoneByFsa(xml, "G1J");

注意事项

如果目标FSA包含单引号(虽然邮政编码场景很少见),必须替换为两个单引号来转义,否则会破坏XPath的语法结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:45:56