c# - 将 XML 映射到 C# 中的类

标签 c# xml attributes deserialization poco

我希望使用 XmlSerializer 对象将嵌套元素中的多个 XML 属性映射到单个 POCO 类中。

XML

<products grand-total="100">
    <one price="50" />
    <two price="20" />
    <tree price="30" />
</products>

POCO

public class Product
{
    public int GrandTotal { get; set; }
    public int OnePrice { get; set; }
    public int TwoPrice { get; set; }
    public int ThreePrice { get; set; }
}

C#

var doc = XDocument.Load("XmlDoc.xml");
var serializer = new XmlSerializer(typeof(Product));
var reader = doc.Root.CreateReader();
var temp = (Product)serializer.Deserialize(reader);

如果有人知道我如何做到这一点,那就太棒了。

谢谢。

最佳答案

如果您被锁定在这个 XML 架构中,这将序列化或反序列化您的 XML 和对象数据:

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

public class ProductsViewModel
{
    public string Xml { get; set; }

    public Product Poco { get; set; }

    public ProductsViewModel()
    {
        Xml = Serialize(new Product());

        Poco = (Product)Deserialize(Xml, typeof(Product));
    }

    public class Price
    {
        [XmlAttribute(AttributeName = "price")]
        public int Value { get; set; }
    }

    [XmlRoot(ElementName = "products")]
    public class Product
    {
        [XmlAttribute(AttributeName = "grand-total")]
        public int GrandTotal { get; set; }

        [XmlElement(ElementName = "one")]
        public Price OnePrice { get; set; }

        [XmlElement(ElementName = "two")]
        public Price TwoPrice { get; set; }

        [XmlElement(ElementName = "tree")]
        public Price ThreePrice { get; set; }

        public Product()
        {
            GrandTotal = 100;
            OnePrice = new Price { Value = 50 };
            TwoPrice = new Price { Value = 20 };
            ThreePrice = new Price { Value = 30 };
        }
    }

    private string Serialize(object obj)
    {
        var serializer = new XmlSerializer(obj.GetType());

        using (var stringWriter = new StringWriter())
        {
            serializer.Serialize(stringWriter, obj);
            return stringWriter.ToString();
        }
    }

    private object Deserialize(string serializedObj, Type type)
    {
        var serializer = new XmlSerializer(type);

        using (var stringReader = new StringReader(serializedObj))
        using (var xmlTextReader = new XmlTextReader(stringReader))
        {
            return serializer.Deserialize(xmlTextReader);
        }
    }
}

关于c# - 将 XML 映射到 C# 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29085381/

相关文章:

c# - 如何使用 Dapper 映射具有不同名称的标识列?

c# - 使用 Intel RealSense 创建 PXCMSenseManager 的区别

python - 如何在Python(elementtree)中向musicXML树添加新元素?

c# - 从 XML 文件中删除所有艺术家节点

c# - 从描述属性中获取枚举

c# - ASP.NET Response.AddHeader 关闭窗口

c# - 如何在 C# 中将 DataRowView 转换为 DataRow

java - XMLInputFactory 是线程安全的吗?

c# - 实体中的相同类别属性与 C# 中的字典

JQuery 属性操作