将XML映射到C#中的类 [英] Mapping XML to classes in c#

查看:74
本文介绍了将XML映射到C#中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking to map multiple XML attributes in nested elements into a single POCO class using the XmlSerializer object.

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

如果有人知道我该怎么做,那就太棒了.

It would be awesome if anyone knows how I can do this.

谢谢.

推荐答案

如果您被锁定在此XML模式中,则会对XML和对象数据进行序列化或反序列化:

If you're locked into this XML schema, this will serialize or de-serialize your XML and object data:

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

这篇关于将XML映射到C#中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆