如何在C#中将嵌套列表转换为XML

时间:2018-01-16 08:37:56

标签: c# xml list xelement xmlconvert

我使用以下方法将列表转换为XML。如何更改此设置以将嵌套列表转换为XML。

private string ConvertProductListToXML(List<ProductDM> productDMList)
{
    var xEle = new XElement("Products",
       from emp in productDMList
       select new XElement("Product",
                    new XElement("ProductID", emp.ProductID),
                      new XElement("Cost", emp.Cost),
                      new XElement("UPC", emp.UPC),
                      new XElement("TaxStatus", emp.TaxStatus)
    ));
    return  ConvertToInnerXML(xEle);
}

public static string ConvertToInnerXML(XElement el)
{
    var reader = el.CreateReader();
    reader.MoveToContent();
    return reader.ReadInnerXml();
}

模型

public class ProductDM
{
    public int? ProductID { get; set; }
    public string UPC { get; set; }
    public string TaxStatus { get; set; }
    public Decimal Cost { get; set; }
}

如果数据模型如下所示,如何使用扩展列表,我该如何修改上述代码。

public class ProductDM
{
    public int? ProductID { get; set; }
    public string UPC { get; set; }
    public string TaxStatus { get; set; }
    public Decimal Cost { get; set; }
    public List<InventoryDM> CabinetList { get; set; }
}

public class InventoryDM
{
    public int InventoryID { get; set; }
}

预期产出:

<Product><ProductID>40</ProductID><Cost>2</Cost><UPC>3121</UPC>
<TaxStatus>NO</TaxStatus><CabinetList>
<InventoryID>1</InventoryID></CabinetList><CabinetList>
<InventoryID>2</InventoryID></CabinetList></Product>

1 个答案:

答案 0 :(得分:2)

我不会使用xElement。 最简单的解决方案是使用xml序列化。 你的课应该像这样更新

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace YourAppNameSpace
{
    [XmlRoot(ElementName="CabinetList")]
    public class InventoryDM {
        [XmlElement(ElementName="InventoryID")]
        public string InventoryID { get; set; }
    }

    [XmlRoot(ElementName="Product")]
    public class Product {
        [XmlElement(ElementName="ProductID")]
        public int? ProductID { get; set; }
        [XmlElement(ElementName="Cost")]
        public Decimal Cost { get; set; }
        [XmlElement(ElementName="UPC")]
        public string UPC { get; set; }
        [XmlElement(ElementName="TaxStatus")]
        public string TaxStatus { get; set; }
        [XmlElement(ElementName="CabinetList")]
        public List<InventoryDM> CabinetList { get; set; }
    }
}

将类序列化为xml

public static string SerializeObject(object obj)
        {
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                serializer.Serialize(ms, obj);
                ms.Position = 0;
                xmlDoc.Load(ms);
                return xmlDoc.InnerXml;
            }
        }