سؤال

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?

هل كانت مفيدة؟

المحلول

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;}
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top