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

Amazon MWS C#客户端库解析Relationships元素报错求助

解决Amazon MWS C# Client库解析Relationships元素的空引用异常问题

我来帮你排查这个空引用异常的问题,结合你给出的XML示例和代码,主要是两个地方出了问题:

1. 未检查Relationships是否为null就直接访问

在MWS返回的Product数据中,并不是所有商品都带有Relationships元素。如果直接访问x.Relationships.Any,当x.Relationships本身为null时,就会抛出"Object reference not set to an instance of an object"异常。

2. 命名空间定义错误

你在处理Relationships的XML时,给XNamespace加了多余的大括号:

XNamespace ns2 = "{http://mws.amazonservices.com/schema/Products/2011-10-01}";

正确的XNamespace定义不需要包裹大括号,直接传入命名空间字符串即可。错误的定义会导致你查找的元素名和XML中的实际元素不匹配,最终element.Element(...)返回null,访问子元素时再次触发空引用。


修正后的代码

下面是调整后的Relationships解析逻辑,加入了null检查和正确的命名空间处理:

ListMatchingProductsResponse lmpr = (ListMatchingProductsResponse)response;
foreach (var x in lmpr.ListMatchingProductsResult.Products.Product)
{
    Console.WriteLine("ASIN: " + x.Identifiers.MarketplaceASIN.ASIN);
    
    // 处理SalesRankings的代码保持不变...
    
    // 修正后的Relationships解析逻辑
    if (x.Relationships != null && x.Relationships.Any != null)
    {
        foreach (var relationship in x.Relationships.Any)
        {
            string xml = ProductsUtil.FormatXml((System.Xml.XmlElement)relationship);
            XElement element = XElement.Parse(xml);
            // 正确定义命名空间,去掉多余的大括号
            XNamespace ns = "http://mws.amazonservices.com/schema/Products/2011-10-01";
            
            // 逐层检查元素是否存在,避免空引用
            var variationParent = element.Element(ns + "VariationParent");
            if (variationParent != null)
            {
                var identifiers = variationParent.Element(ns + "Identifiers");
                if (identifiers != null)
                {
                    Console.WriteLine("Variation Parent Identifiers: " + identifiers.ToString());
                    // 如果需要提取ASIN,可以继续处理
                    var marketplaceAsin = identifiers.Element(ns + "MarketplaceASIN");
                    if (marketplaceAsin != null)
                    {
                        var parentAsin = marketplaceAsin.Element(ns + "ASIN")?.Value;
                        Console.WriteLine("Variation Parent ASIN: " + parentAsin);
                    }
                }
            }
        }
    }
    
    // 处理AttributeSets的代码保持不变...
    
    lstASIN.ASIN.Add(x.Identifiers.MarketplaceASIN.ASIN);
    Console.WriteLine("");
}

额外建议

  • 防御性编程:对于MWS返回的所有可选元素,都要先检查是否为null再访问属性,也可以用C#的空传播运算符?.简化代码(比如variationParent?.Element(ns + "Identifiers"))
  • 区分命名空间:注意Relationships和AttributeSets使用的是不同的命名空间,不要混淆(前者是http://mws.amazonservices.com/schema/Products/2011-10-01,后者是http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd)
  • 优先使用实体类:如果你的MWS Client库自动生成了对应Relationships的实体类(比如VariationParentType),直接通过x.Relationships.VariationParent访问会比手动解析XML更可靠,也更易维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:53:00