【问题标题】:How to Creating Dynamic Object from XML with type and Attribute Names in C#?如何在 C# 中使用类型和属性名称从 XML 创建动态对象?
【发布时间】:2020-11-06 00:07:19
【问题描述】:
<root>
  <source>
    <fields>
      <string propertyName="Status" class="System.String" nullable="true" valueInputType="all" displayName="status" description="Condition" maxLength="150" />
      
      <function methodName="Calculator" displayName="Calculator" includeInCalculations="true">
        <parameters>
          <input valueInputType="all" class="System.String" type="string" nullable="true" maxLength="256" />
        </parameters>
        <returns valueInputType="all" class="System.Double" type="numeric" nullable="false" min="-9007199254740992" max="9007199254740992" allowDecimal="true" allowCalculation="true" />
      </function>
    </fields>
  </source>
</root>

我必须生成一个类似于此 XML 的对象,如下所示:

[Field(DisplayName = "Status", Max = 150, Description = "Condition")]
        public string Status;
[Method(DisplayName = "Calculator")]
        public double Calculator(string st)
        {
            double num = st.length();
            return num;
        }

即使我收到 Object 的类型没问题,我什至可能都不会直接使用该对象。

【问题讨论】:

    标签: c# xml xml-parsing dynamicobject


    【解决方案1】:

    试试这样的

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication11
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
                var fields = GetFields(doc);
            }
            static object GetFields(XDocument doc)
            {
                var results = doc.Descendants("fields").Select(x => new
                {
                    Status = (string)x.Element("string").Attribute("propertyName"),
                    Max = (int)x.Element("string").Attribute("maxLength"),
                    Description = (string)x.Element("string").Attribute("description"),
                    Calculator = (double?)x.Element("returns")
    
                }).ToList();
    
                return results;
            }
        }
     
    
    }
    

    【讨论】:

    • 我必须使用 typebuilder 和 ILGenerator 动态生成对象
    • 您有什么要求?您如何知道要从 xml 中提取哪些属性/元素?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2020-10-24
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    相关资源
    最近更新 更多