How to create c# objects using xml

大憨熊 提交于 2020-01-02 09:29:13

问题


I am new to C#, Silverlight 5 and XAML beginner. I am working on a VS-2012 project and I don't have to use any CycleClip Board Ring to do this task. I have an XML file in my VS project. Suppose the file is given below:

FileName is FileXml.xml   

<?xml version="1.0" encoding="utf-8" ?>
   <parameter>
   <name>mounts</name>
    <unit></unit>
      <component>
         <type>List</type>
         <attributes>
            <type>Integer</type>
            <displayed>4</displayed>
            <add_remove>yes</add_remove>
            <item>25</item>
         </attributes>
         <attributes>
            <ccypair>XAUUSD</ccypair>
            <item>100</item>
         </attributes>
      </component >
   </parameter>

And I have to parse this XML file and have to create the object in C# .So that I would be able to use "bands_amounts" (name) and all other elements accessing through those objects. How to do this using C# code?


回答1:


You will want to use some sort of de-serialization. Here is an example of one I implemented not too long ago:

public static class Serialization<T> where T : class   
{    

    public static T DeserializeFromXmlFile(string fileName)
    {
        if (!File.Exists(fileName))
        {
            return null;
        }

        DataContractSerializer deserializer = new DataContractSerializer(typeof(T));

        using (Stream stream = File.OpenRead(fileName))
        {
            return (T)deserializer.ReadObject(stream);
        }
    }
}

Then to call it you would do something like this:

Serialization<YourCustomObject>.DeserializeFromXmlFile(yourFileNameOrPath);

Remember that you would have to have a Class that corresponds to the XML you want to de-serialized. (aka turn into an object).

Your class would look something like this:

[Serializable]
class parameter
{
     [Datamember]
     public string name {get; set;}

     [Datamember]
     public string label {get; set;}

     [Datamember]
     public string unit {get; set;}

     [Datamember]
     public component thisComponent {get; set;}
}

[Serializable]
class component
{
    [Datamember]
    public string type {get; set;}

    [Datamember]
    public List<attribute> attributes  {get; set;}
}

[Serializable]
class attribute
{
    [Datamember]
    public string? type {get; set;}

    [Datamember]
    public string? displayed {get; set;}

    [Datamember]
    public string? add_remove {get; set;}

    [Datamember]
    public string? ccypair {get; set;}

    [Datamember]
    public List<int> item { get; set;}
}


来源:https://stackoverflow.com/questions/23369197/how-to-create-c-sharp-objects-using-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!