这是我的情景: 我有一个应用程序,可以下载xml文件并从中提取数据。为此,我创建了一个xml配置文件,如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<labelsSets>
<labelsSet getUrl="https://www.address.com/services/rest/product-display.xml?expand_entities=0&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”和“tableField”属性添加到“field”节点,但是我找不到实现提取值和db类之间映射的方法。
答案 0 :(得分:0)
试试这个
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;}
}