如何将XML转换为.net对象. [英] How to convert XML into .net objects.

查看:139
本文介绍了如何将XML转换为.net对象.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要开发一个应用程序,该应用程序将XML文件作为输入并返回.NET对象.

我已经使用Deserialize方法进行了尝试,但是问题是Deserialize方法希望我们知道我们要创建的对象的类型,我的问题是我将获得不同的XML,并且我想要一个通用代码,该代码可以接受任何XML并返回一个.NET对象.

我不知道这是否可能.

有人可以帮我吗?

代码示例将受到高度赞赏.

谢谢

Hi,

I need to develop an application, which takes an XML file as an input and returns a .NET object.

I have tried this using the Deserialize method, but the problem is Deserialize method expects us to know the type of the object we want to create, my problem is that I will get different XML''s and I want a generic code, which can take any XML and returns a .NET object.

I dont know whether it is possible or not.

Can some please help me in this?

A code sample will be highly appreciated.

Thanks

推荐答案

如果您的XML结构是完全任意的(我的意思是,它可以具有具有任何嵌套级别的任何层次结构的任何结构),很抱歉,它不是可以即时生成.NET对象.

如果需要为每个不同的XML(具有不同的结构)返回一个类型化的.NET对象,则肯定需要知道XML的结构,进行相应的解析并填充该对象.别无选择.
If your XML structure is completely arbitrary (I mean, it could have any structure having any hierarchy with any nesting level), I am sorry, it is not possible to generate a .NET object on the fly.

If you need to return a typed .NET object for each different XML (Of different structure), you surely need to know the structure of the XML, parse it accordingly and populate the object. There is no alternative.


我不太清楚你的意思.但是您不能将任何xml转换为任何.Net对象.
首先,您的应用程序必须知道xml的属性/元素应该是什么类型.
为此,您应该具有xsd模式.
假设您具有以下xml:

I''m not quite sure what you''ve meant. But you cannot convert ANY xml into ANY .Net object.
First your app have to know what types should be xml''s attributes/elements.
You should have xsd schema for this purpose.
Let''s suppose you have the following xml:

<BillsOutList>
  <BillOut Account="5"

           Destination="RUFBESTQWY"

           Created="2010-12-14T11:34:48.297"

           Modified="2010-12-14T11:34:48.297"

           Amount="10.0000"

           PageNumber="0" />
  <BillOut Account="5"

           Destination="RUFBESTQWY"

           Created="2010-11-22T17:41:25.330"

           Modified="2010-11-22T17:41:25.330"

           Amount="10.0000"  />
</BillsOutList>



xsd应该是:



The xsd should be:

<xs:schema

  id="IncomeList" xmlns=""

  xmlns:xs="http://www.w3.org/2001/XMLSchema"

  xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="BillsOutList"

              msdata:Locale="en-US">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="1">
        <xs:element name="BillOut">
          <xs:complexType>
            <xs:attribute name="Account" type="xs:string" />
            <xs:attribute name="Destination" type="xs:string" />
            <xs:attribute name="Created" type="xs:string" />
            <xs:attribute name="Modified" type="xs:string" />
            <xs:attribute name="Amount" type="xs:decimal" />
            <xs:attribute name="PageNumber" type="xs:int" />
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>



和对应的类:



And the corresponding class:

public class BillOut : IEntity
 {
     private string msAccount = String.Empty;
     private decimal mdAmount;
     private DateTime moModified;
     private DateTime moCreated;
     private string msDestination = String.Empty;
     private int miPage;

     [XmlAttribute]
     public string Destination
     {
         get { return msDestination; }
         set { msDestination = value; }
     }

     [XmlAttribute]
     public DateTime Created
     {
         get { return moCreated; }
         set { moCreated = value; }
     }

     [XmlAttribute]
     public DateTime Modified
     {
         get { return moModified; }
         set { moModified = value; }
     }

     [XmlAttribute]
     public decimal Amount
     {
         get { return mdAmount; }
         set { mdAmount = value; }
     }

     [XmlAttribute]
     public string Account
     {
         get { return msAccount; }
         set { msAccount = value; }
     }

     [XmlAttribute]
     public int PageNumber
     {
         get { return miPage; }
         set { miPage = value; }
     }
     public string GetXSD()
     {
         return "BillsOutList.xsd";
     }
 }




这是IEntity:




Here is the IEntity:

public interface IEntity
{
    string GetXSD();
}




并进行转换:




And to convert it:

Type TType = typeof(T);
if (TType.GetInterface("IEntity") == null)
{
    RowCount = 0;
    throw new CPException(TType.ToString() + " must be iherited from IEntity!");
}
string lsXSDFile = String.Empty;

try
{
    T t = Activator.CreateInstance<T>();
    lsXSDFile = (string)TType.InvokeMember("GetXSD", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, t, null);
}
catch (Exception)
{
    RowCount = 0;
    throw new CPNullException(TType.ToString() + " no XSD!");
}

// check resources
DataSet loDataSet = new DataSet();
Stream schema = Assembly.GetExecutingAssembly().GetManifestResourceStream("yourappnamespaces.Schemas." + lsXSDFile);
if (schema == null)
{
    RowCount = 0;
    throw new CPNullException(lsXSDFile + " No schema in resources!");
}

loDataSet.ReadXmlSchema(schema);





//fill the data
XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "\t";
            MemoryStream loResultStream = new MemoryStream();
            XmlWriter writer = XmlWriter.Create(loResultStream, settings);
            yourxmlelement.WriteTo(writer);
            writer.Close();
            loResultStream.Position = 0;
            loDataSet.ReadXml(loResultStream, XmlReadMode.IgnoreSchema);
            loResultStream.Close();



但是,如果可以使用.Net 4,则可以使用CodeDOM/Reflection.Emit动态创建对象,但仍然需要xsd才能知道属性的类型.



But if you can use .Net 4 you can use CodeDOM/Reflection.Emit to create an object dynamically but still you need xsd to know types of properties.


您不能直接转换xml到强类型的.net对象.
解决方案:
1)使用XmlSerializer类,该类将xml反序列化为对象,但是必须正确设置其格式.
2)编写自己的解析和对象创建.
You can''t directly convert xml to strong typed .net objects.
Solutions:
1) Use XmlSerializer class, which, deserializes your xml to objects, but, it has to be properly formated.
2) Write your own parsing, and object creation.


这篇关于如何将XML转换为.net对象.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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