Namecheap API: XML reader C# 异常

Namecheap API: XML reader exception in C#

我在反序列化 XML 时遇到问题:

[XmlRoot("ProductCategory")]
public class ProductCategory
{
    public Product[] Products;
}

public class Product
{
    [XmlArray("Product")]
    [XmlArrayItem("ProductPrice", typeof(ProductPrice))]
    public ProductPrice[] Prices;
}

public class ProductPrice
{
    [XmlAttribute]
    public int Duration;

    [XmlAttribute]
    public string DurationType;

    [XmlAttribute]
    public decimal Price;

    [XmlAttribute]
    public decimal RegularPrice;

    [XmlAttribute]
    public decimal YourPrice;

    [XmlAttribute]
    public string CouponPrice;

    [XmlAttribute]
    public string Currency;
}

这是动作:

public ProductType GetPricing()
        {
            XDocument doc = new Query(_params)
              .AddParameter("ProductType", "DOMAIN")
              .AddParameter("ActionName","REGISTER")
              .Execute("namecheap.users.getPricing");

            var serializer = new XmlSerializer(typeof(ProductType), _ns.NamespaceName);

            using (var reader = doc.Root.Element(_ns + "CommandResponse").Element(_ns + "ProductType").CreateReader())
            {
                return (ProductType)serializer.Deserialize(reader);
            }
        }

我收到这个错误: NullReferenceException: Object reference not set to an instance of an object.

在这里您可以找到 xml 的示例:https://www.namecheap.com/support/api/methods/users/get-pricing.aspx

有什么想法吗?

发现您的代码存在多个问题。这是工作代码

首先你必须有如下定义的对象

[XmlRoot("ProductType", Namespace = "http://api.namecheap.com/xml.response")]
public class ProductType
{
    [XmlAttribute("Name")]
    public string Name { get; set; }

    [XmlElement("ProductCategory")]
    public ProductCategory[] ProductCategories;
}
public class ProductCategory
{
    [XmlElement("Product")]
    public Product[] Products;
}

public class Product
{
    [XmlElement("Price")]
    public ProductPrice[] Prices;
}

public class ProductPrice
{
    [XmlAttribute]
    public int Duration;

    [XmlAttribute]
    public string DurationType;

    [XmlAttribute]
    public decimal Price;

    [XmlAttribute]
    public decimal RegularPrice;

    [XmlAttribute]
    public decimal YourPrice;

    [XmlAttribute]
    public string CouponPrice;

    [XmlAttribute]
    public string Currency;
}

这是反序列化它的代码

var serializerx = new XmlSerializer(typeof(ProductType), "http://api.namecheap.com/xml.response");
XElement doc = XElement.Load("sample1.xml");
XNamespace ns = doc.Name.Namespace;
var e = doc.Element(ns + "CommandResponse").Element(ns + "UserGetPricingResult").Element(ns + "ProductType");

using (var reader = e.CreateReader())
{
    var prod =  (ProductType)serializerx.Deserialize(reader);
}

希望对您有所帮助