user1687824
user1687824

Reputation: 807

Deserialization of key value pair in XML to c# object

I have XML as shown below.

 <Device-array>
   <Device>
    <id>8</id>
    <properties>
     <PropKeyValuePair>...</PropKeyValuePair>
     <PropKeyValuePair>...</PropKeyValuePair>
    </properties>
   </Device>
   <Device>...</Device>
   <Device>...</Device>
 </Device-array>

I am planning to deserialize it to C# object so that it will be faster. I only require the id field. But i understand that the class need to have an array for (properties). But how do i represent the key valuepair ?

[Serializable()]
public class SLVGeoZone
{
    [XmlElement("id")]
    public string id { get; set; } 

    //Arraylist of key value pairs here ?

 }

need suggetions.

Upvotes: 0

Views: 977

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

You can use LINQ to XML instead of deserialization and get just what you need: list of ids:

var xDoc = XDocument.Load("FilePath.xml");

var ids = xDoc.Root
              .Elements("Device")
              .Select(x => (int)x.Element("id"))
              .ToList();

If you really need to use deserialization you can just omit properties you don't need and XmlSerializer will deserialize just declared content, skipping elements you didn't declare in your class.

Update

To get more then just a name into list of anonymous type:

var ids = xDoc.Root
              .Elements("Device")
              .Select(x => new {
                  Id =  (int)x.Element("id"),
                  Name = (string)x.Element("name")
              })
              .ToList();

Upvotes: 1

Related Questions