动态地将值映射到类属性

本文关键字:属性 映射 动态 | 更新日期: 2023-09-27 17:50:44

这是我的场景:我有一个应用程序,可以下载xml文件并从中提取数据。为此,我创建了一个xml配置文件,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<labelsSets>
    <labelsSet getUrl="https://www.address.com/services/rest/product-display.xml?expand_entities=0&amp;limit=100000000">
        <fields>
            <field name="item" required="true" xPath="result/item" doGet="false" isRoot="true" />
            <field name="Title" required="true" xPath="title" doGet="false" />
        </fields>
    </labelsSet>
</labelsSets>

其中"field"节点是我必须从下载的xml中提取的值。因此,我必须将数据插入到数据库中,我使用EF DbContext Generator:

生成了这样的类
[Table("Winery")]
public partial class Winery
{
    public Winery()
    {
        Wine = new HashSet<Wine>();
    }
    [StringLength(10)]
    public string Id { get; set; }
    [Required]
    [StringLength(200)]
    public string Name { get; set; }
    public DateTime? LastUpdate { get; set; }
    public virtual ICollection<Wine> Wine { get; set; }
}

是否有一种方法将提取的值从xml映射到db表类?

我想在配置中添加"table"answers"tableField"属性到"field"节点,但我找不到实现提取值和db类之间映射的方法。

动态地将值映射到类属性

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:'temp'test.xml";
        static void Main(string[] args)
        {
            //alternate method
            //DataSet ds = new DataSet();
            //ds.ReadXml(FILENAME);
            XmlSerializer xs = new XmlSerializer(typeof(LabelsSets));
            XmlTextReader reader = new XmlTextReader(FILENAME);
            LabelsSets labelSets = (LabelsSets)xs.Deserialize(reader);

        }
    }
}
[XmlRoot("labelsSets")]
public class LabelsSets
{
    [XmlElement("labelsSet")]
    public List<LabelsSet> labelSet {get;set;}
}
[XmlRoot("labelsSet")]
public class LabelsSet
{
    [XmlAttribute("getUrl")]
    public string getUrl {get;set;}
    [XmlElement("fields")]
    public Fields fields {get;set;}
}
[XmlRoot("fields")]
public class Fields
{
    [XmlElement("field")]
    public List<Field> fields {get;set;}
}
[XmlRoot("field")]
public class Field
{
    [XmlAttribute("name")]
    public string name {get;set;}
    [XmlAttribute("required")]
    public Boolean required {get;set;}
    [XmlAttribute("xPath")]
    public string xPath {get;set;}
    [XmlAttribute("doGet")]
    public Boolean doGet {get;set;}
    [XmlAttribute("isRoot")]
    public Boolean isRoot {get;set;}
}