-1

我在反序列化 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:未将对象引用设置为对象的实例。

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

有任何想法吗?

4

1 回答 1

1

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

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

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

希望这可以帮助

于 2018-01-23T02:15:21.133 回答