Namecheap API:C#中的XML阅读器异常

时间:2018-01-22 20:51:12

标签: c# xml xmlserializer xmlreader namecheap

我在反序列化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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

发现您的代码存在的问题数量。这是工作代码

首先,您必须将对象定义如下

[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);
}

希望这有帮助

相关问题