我正在使用XMLSerializer
将复杂的C#对象序列化为XML文档。我面临的问题是序列化之后,我得到了一个不应该存在的子容器层。我不确定它如何被序列化为。我的对象结构如下:
[XmlRoot(ElementName = "order")]
public class order
{
[XmlElement(ElementName = "orderNumber")]
public string OrderNumber { get; set; }
[XmlElement(ElementName = "products")]
public Products Products { get; set; }
}
[XmlRoot(ElementName = "products")]
public class Products
{
[XmlElement(ElementName = "product")]
public List<Product> Product { get; set; }
}
[XmlRoot(ElementName = "product")]
public class Product
{
[XmlElement(ElementName = "quantity")]
public decimal Quantity { get; set; }
[XmlElement(ElementName = "part")]
public string part { get; set; }
[XmlElement(ElementName = "unitPrice")]
public decimal UnitPrice { get; set; }
}
我想将其序列化为订单/产品/产品,但是,它已经序列化为订单/产品/产品/产品:
<order>
<orderNumber>1</orderNumber>
<products>
<product>
<product>
<quantity>1</quantity>
<part>222584</part>
<unitPrice>5.0</unitPrice>
</product>
<product>
<quantity>5</quantity>
<part>222</part>
<unitPrice>1.0</unitPrice>
</product>
<product>
<quantity>15</quantity>
<part>222244</part>
<unitPrice>12.0</unitPrice>
</product>
</product>
</products>
</order>
答案 0 :(得分:1)
要删除产品上的多余标签,则您的xml序列化类应如下:
[XmlRoot(ElementName = "order")]
public class order
{
[XmlElement(ElementName = "orderNumber")]
public string OrderNumber { get; set; }
[XmlElement(ElementName = "products")]
public List<Product> Products { get; set; }
}
编写当前的类结构以创建层次结构
[XmlRoot(ElementName = "order")]
[XmlElement(ElementName = "products")]
[XmlElement(ElementName = "product")]
[XmlRoot(ElementName = "product")]<-Final Product data here
不需要下面的额外层,只需在订单中直接使用列表即可。
[XmlRoot(ElementName = "products")]
public class Products
{
[XmlElement(ElementName = "product")]
public List<Product> Product { get; set; }
}