简体   繁体   English

从动态xml转换为c#对象

[英]convert from dynamic xml to c# object

I need inputs in converting an dynamic xml to defined c# object model 我需要输入将动态xml转换为定义的c#对象模型

My sample xml is as below : 我的样本xml如下:

<?xml version="1.0" encoding="utf-8" ?>
  <Persons>
    <Person>
      <Id>10</Id>
      <FirstName> Dino </FirstName>
      <LastName> Esposito </LastName>
      <Addresses>
        <Address>
          <AddressType>BillTo</AddressType>
          <Street1></Street1>
          <Street2></Street2>
          <Street3></Street3>
          <City>Moscow</City>
        </Address>
        <Address>
          <AddressType>ShipTo</AddressType>
          <Street1></Street1>
          <Street2></Street2>
          <Street3></Street3>
          <City>Moscow</City>
        </Address>
        <Address>
          <AddressType>Contact</AddressType>
          <Street1></Street1>
          <Street2></Street2>
          <Street3></Street3>
          <City>Moscow</City>
        </Address>
      </Addresses>
    </Person>
  </Persons>

I am expecting the values of this xml to be converted to C# object at run time. 我希望在运行时将此xml的值转换为C#对象。 I would want an object similar to the following to be defined: My Expected class object C# is as below: 我希望定义一个类似于下面的对象:我的预期类对象C#如下:

public class Person
{
    public int Id { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public IList<Address> Addresses { get; set; }
}

public class Address
{
    public string AddressType { get; set; }
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    public string Street3 { get; set; }
    public string City { get; set; }
}

I went through dynamic and ExpandoObject in C# 4.0, this approach is allowing me to get values dynamically by using keys. 我在C#4.0中经历了动态和ExpandoObject,这种方法允许我通过使用键动态获取值。 I dont know how i can populate these to my datamodel. 我不知道如何将这些填充到我的数据模型中。

Note: I dont want to define this class model structure, this keeps changing over period of time. 注意:我不想定义这个类模型结构,这会在一段时间内不断变化。 I am looking for a solution which allows me to get values like DynamicObject.Addresses.Address[0].City. 我正在寻找一个解决方案,它允许我获取像DynamicObject.Addresses.Address [0] .City这样的值。

Kindly give your inputs. 请提供您的意见。

A solution using LINQ2XML can look like this (no classes needed): 使用LINQ2XML的解决方案可能如下所示(不需要类):

var xml = XDocument.Parse(xmlSrc); // from XML string, e.g.: <xml ...><Persons><Person>...
//var xml = XDocument.Load(xmlFile); // from XML file, e.g.: c:\temp\persons.xml

var persons = xml.Root.Elements("Person").ToList();
var p1Addresses = persons[0].Elements("Addresses").ToList();
foreach (var address in p1Addresses.Elements("Address"))
{
    var elementAddress = address.Element("AddressType");
    var elementCity = address.Element("City");
    System.Console.WriteLine(string.Format("{0} - {1}", elementAddress.Value, elementCity.Value));
}

The output is: 输出是:

BillTo - Moscow
ShipTo - Moscow
Contact - Moscow

I would suggest you read this article: http://www.codeproject.com/Articles/62839/Adventures-with-C-4-0-dynamic-ExpandoObject-Elasti . 我建议你阅读这篇文章: http//www.codeproject.com/Articles/62839/Adventures-with-C-4-0-dynamic-ExpandoObject-Elasti There is a way to construct dynamic object from XML. 有一种方法可以从XML构造动态对象。 Or this article: http://www.codeproject.com/Articles/461677/Creating-a-dynamic-object-from-XML-using-ExpandoOb . 或者这篇文章: http//www.codeproject.com/Articles/461677/Creating-a-dynamic-object-from-XML-using-ExpandoOb Take whatever you need and you can customize the code for your needs. 随心所欲,您可以根据需要自定义代码。

Check this example: 检查此示例:

        string xml =
            @"<?xml version='1.0' encoding='utf-8' ?>
              <Persons>
               <Person>
                <Id>10</Id>
                <FirstName> Dino </FirstName>
                <LastName> Esposito </LastName>
                <Addresses>
                  <Address>
                   <AddressType>BillTo</AddressType>
                   <Street1></Street1>
                   <Street2></Street2>
                   <Street3></Street3>
                   <City>Moscow</City>
                </Address>
                <Address>
                 <AddressType>ShipTo</AddressType>
                 <Street1></Street1>
                 <Street2></Street2>
                 <Street3></Street3>
                 <City>Moscow</City>
                </Address>
                <Address>
                  <AddressType>Contact</AddressType>
                  <Street1></Street1>
                  <Street2></Street2>
                  <Street3></Street3>
                  <City>Moscow</City>
                </Address>
             </Addresses>
            </Person>
           </Persons>";

        XElement root = XElement.Parse(xml);

        IEnumerable<XElement> list = root.XPathSelectElements("./Person/Addresses/Address[2]/City");
        foreach (XElement el in list)
            Console.WriteLine(el);
        Console.ReadLine();

You will get: <City>Moscow</City> 您将获得: <City>Moscow</City>

Or look at this solution using DynamicObject : 或者使用DynamicObject查看此解决方案:

    XElement root = XElement.Parse(xml);
    dynamic persons = DynamicXml.Parse(xml);
    Console.WriteLine(persons.Person.Addresses.Address[1].City);

Deserialize XML To Object using Dynamic 使用Dynamic将XML反序列化为对象

感谢大家的投入,我正在寻找的解决方案可以在这个位置获得http://www.codeproject.com/Tips/227139/Converting-XML-to-an-dynamic-object-using-ExpandoO

I've created a project specifically for this purpose, as I was dissatisfied with the alternatives (such as the CodeProject article linked to in other answers). 我已经专门为此目的创建了一个项目,因为我对替代方案不满意(例如在其他答案中链接的CodeProject文章)。

I've posted it on Github: https://github.com/jonathanconway/XmlToDynamic . 我已经在Github上发布了它: https//github.com/jonathanconway/XmlToDynamic

I would rather not post the source code here, as it's too big, but here's the usage: 我不想在这里发布源代码,因为它太大了,但是这里是用法:

var xmlString =
    @"<addressBook>
       <contacts>
         <contact>
           <name>Jonathan</name>
         </contact>
       </contacts>
     </addressBook>";
var dynamicXml = XElement.Parse(xmlString).ToDynamic();
var firstPersonsName = dynamicXml.contacts[0].name.Value;
// firstPersonsName will be 'Jonathan'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM