我正在从web api中检索xml数据并将数据反序列化为对象。:
<Result>
<VendorInfo xml:lang="xx">
<Vendor vname="A" cpe="B">
<Product pname="C" cpe="D"/>
</Vendor>
<Vendor vname="E" cpe="F">
<Product pname="G" cpe="H"/>
</Vendor>
<Vendor vname="I" cpe="J">
<Product pname="K" cpe="L"/>
<Product pname="M" cpe="N"/>
</Vendor>
</VendorInfo>
<Status keyword="hoge" feed="bar"/>
</Result>
我目前的代码是:
[XmlRoot(ElementName = "Product")]
public class Product
{
[XmlAttribute(AttributeName = "pname")]
public string Pname { get; set; }
[XmlAttribute(AttributeName = "cpe")]
public string Cpe { get; set; }
}
[XmlRoot(ElementName = "Vendor")]
public class Vendor
{
[XmlArrayItem(ElementName = "Product")]
public List<Product> Product { get; set; }
[XmlAttribute(AttributeName = "vname")]
public string Vname { get; set; }
[XmlAttribute(AttributeName = "cpe")]
public string Cpe { get; set; }
}
[XmlRoot(ElementName = "VendorInfo")]
public class VendorInfo
{
[XmlElement(ElementName = "Vendor")]
public List<Vendor> Vendor { get; set; }
[XmlAttribute(AttributeName = "lang")]
public string Lang { get; set; }
}
[XmlRoot(ElementName = "Status")]
public class Status
{
[XmlAttribute(AttributeName = "feed")]
public string Feed { get; set; }
[XmlAttribute(AttributeName = "keyword")]
public string Keyword { get; set; }
}
[XmlRoot(ElementName = "Result")]
public class Result
{
[XmlElement(ElementName = "VendorInfo")]
public VendorInfo VendorInfo { get; set; }
[XmlElement(ElementName = "Status")]
public Status Status { get; set; }
}
但是,此代码无法正常工作。 只反序列化前2个Vendor元素,不反序列化Product元素。 我做错了什么?
最好的问候
答案 0 :(得分:0)
你几乎没有什么可以照顾的。
只制作一个元素XmlRoot
。请参阅以下链接并搜索&#34;使用XmlRootAttribute和XmlTypeAttribute控制类的序列化&#34;。
在您的情况下,&#34;结果&#34; class是root。
全部休息XmlType
。
在供应商类而不是&#34; XmlArrayItem&#34;中,只需&#34; XmlElement&#34;。
这是工作代码。
[XmlType("Product")]
public class Product
{
[XmlAttribute(AttributeName = "pname")]
public string Pname { get; set; }
[XmlAttribute(AttributeName = "cpe")]
public string Cpe { get; set; }
}
[XmlType("Vendor")]
public class Vendor
{
[XmlElement(ElementName = "Product")]
public List<Product> Product { get; set; }
[XmlAttribute(AttributeName = "vname")]
public string Vname { get; set; }
[XmlAttribute(AttributeName = "cpe")]
public string Cpe { get; set; }
}
[XmlType("VendorInfo")]
public class VendorInfo
{
[XmlElement(ElementName = "Vendor")]
public List<Vendor> Vendor { get; set; }
[XmlAttribute(AttributeName = "xml:lang")]
public string Lang { get; set; }
}
[XmlType("Status")]
public class Status
{
[XmlAttribute(AttributeName = "feed")]
public string Feed { get; set; }
[XmlAttribute(AttributeName = "keyword")]
public string Keyword { get; set; }
}
[XmlRoot(ElementName = "Result")]
public class Result
{
[XmlElement(ElementName = "VendorInfo")]
public VendorInfo VendorInfo { get; set; }
[XmlElement(ElementName = "Status")]
public Status Status { get; set; }
}