Click here to Skip to main content
14,924,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Below is my XML file:
<Course>
  <CourseInfo>
    <Id>3000</Id>
    <Name type="BTECH">Bachelor of Technology</Name>
  <CourseInfo>
</Course>



I would like to deserialize this XML.
I created classes for Course and CourseInfo.
When I tried to deserialize the xml using below code, I got Id as "3000" and Name as "Bachelor of Technology", but didn't get the type attribute.
Please guide me to get the value of type attribute.
Thanks in advance

public class CourseInfo
{
   public string m_Id;
   [XmlElement("Id")]
   public string Id
   {
      get { return m_Id; }
      set { m_Id = value; }
   }

   public string m_Name;
   [XmlElement("Name")]
   public string Name
   {
      get { return m_Name; }
      set { m_Name = value; }
   }
}
Posted
Updated 10-Jan-11 23:39pm
v2

I would write an xml schema for the xml file and use
xsd.exe[^] to generate the code.

Regards
Espen Harlinn
   
I would try to refactor the solution if possable to use a DataContract. Not that your exactly using Data Contracts, but they are another option.

You cannot use the DataContract to get attributes unfortunatly... it simply can't be done. You need to make the XML have only values inside the tags, no attributes.

I've seen some very round about ways to do this but in the long run it becomes way too much work (practically requires an extra library :omg: ..!!) it is just better to do this with XML transforms if you MUST have that attribute there or just refactor the XML (if you can) to be something more like:
<Course>
  <CourseInfo>
    <Id>3000</Id>
    <Name type="BTECH">Bachelor of Technology</Name>
  <CourseInfo>
</Course>


Becomes:
<Course>
  <CourseInfo>
    <Id>3000</Id>
    <Name>
     <type>BTECH"</type>
     <value>Bachelor of Technology</value>
    </Name>
  <CourseInfo>
</Course>

MSFT doesn't use attributes in DataContracts.

sorry I know it isn't exactly what you were asking but I really like using Data Contracts.. so I evangelise. :-D
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900