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

如何在XmlDocument中筛选行:仅保留Category为Business的记录

问题场景

我有一个包含XML列(xmlColumn1)的SQL Server表,该列中的XML数据示例如下:

<!--Row 1--column (xmlColumn1)
<parameters>
    <Category>Business</Category>
    <Region>CCF25F36-B2A7-4790-82A4-7EC5E016C197</Region>
    <CountryId>EC7333E0-7BEE-4913-9973-2FCABE3DA6F0</CountryId>
</parameters>

<!--Row 2--column (xmlColumn1)
<parameters>
    <Category>Politics</Category>
    <Region>CCF25F36-B2A7-4790-82A4-7EC5E016C197</Region>
    <CountryId>EC7333E0-7BEE-4913-9973-2FCABE3DA6F0</CountryId>
</parameters>

<!--Row 3--column (xmlColumn1)
<parameters>
    <Category>Business</Category>
    <Region>CCF25F36-B2A7-4790-82A4-7EC5E016C197</Region>
    <CountryId>EC7333E0-7BEE-4913-9973-2FCABE3DA6F0</CountryId>
</parameters>

<!--Row 4--column (xmlColumn1)
<parameters>
    <Category>Sports</Category>
    <Region>CCF25F36-B2A7-4790-82A4-7EC5E016C197</Region>
    <CountryId>EC7333E0-7BEE-4913-9973-2FCABE3DA6F0</CountryId>
</parameters>

我使用以下SQL语句查询数据:

SELECT Id, xmlColumn1
FROM MyTable

查询结果被加载到C#列表中:

List<myData> Data = MyDataSource.GetMyData();

当前处理数据并添加到另一个列表的代码如下(已修正两处笔误:Data.Count.Count改为Data.Count,x.id改为x.xmlColumn1):

if (Data.Count > 0)
{
    Data.ForEach(x =>
    {
        var xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(x.xmlColumn1);
        XmlNodeList paramsList = xmlDocument.SelectNodes("//Region");

        foreach (XmlNode node in paramsList)
        {
            MyOtherList.Add(new OtherList { Id = x.Id, Region = new Guid(node.InnerText) });
        }
    });
}

需求:添加条件,仅将XML列中Category为"Business"的行添加到MyOtherList,非Business的行跳过添加操作。


解决方案

方案一:在C#代码中添加判断逻辑

修改处理代码,先读取Category节点的值,判断符合条件后再执行添加操作:

if (Data.Count > 0)
{
    Data.ForEach(x =>
    {
        var xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(x.xmlColumn1);
        
        // 获取Category节点并判断值
        XmlNode categoryNode = xmlDocument.SelectSingleNode("//Category");
        if (categoryNode != null && categoryNode.InnerText.Equals("Business", StringComparison.OrdinalIgnoreCase))
        {
            XmlNodeList paramsList = xmlDocument.SelectNodes("//Region");
            foreach (XmlNode node in paramsList)
            {
                MyOtherList.Add(new OtherList { Id = x.Id, Region = new Guid(node.InnerText) });
            }
        }
    });
}

说明:

  • 用SelectSingleNode直接获取单个Category节点,适配你的XML结构(每个parameters下只有一个Category)
  • 增加空值判断,避免XML中无Category节点引发空引用异常
  • StringComparison.OrdinalIgnoreCase用于忽略大小写匹配,若需严格区分大小写可移除该参数

方案二:在SQL查询阶段直接过滤(更高效)

如果不需要获取非Business分类的数据,建议直接在SQL层过滤,减少数据传输量和后续处理压力:

SELECT Id, xmlColumn1
FROM MyTable
WHERE xmlColumn1.exist('/parameters/Category[text()="Business"]') = 1

查询结果仅包含Category为Business的行,后续C#代码无需额外判断,直接按原有逻辑处理即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:35:32