Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello friend,

I am doing some web application where I am getting return xml as string as follows.
HTML
<siteconfigurationinfor>\n  <id>11</id>\n  <siteid>DELH2I-4004-20</siteid>\n  <sectors />\n  <omini />\n  <micro />\n  <macro />\n  <sitesector>\n    <sectorid>31</sectorid>\n    <sectorname>Sector1</sectorname>\n    <clearance />\n    <azimuth />\n    <heightfromggound />\n    <mounttype />\n    <anttype />\n    <tilt />\n  </sitesector>\n  <sitesector>\n    <sectorid>32</sectorid>\n    <sectorname>Sector2</sectorname>\n    <clearance />\n    <azimuth />\n    <heightfromggound />\n    <mounttype />\n    <anttype />\n    <tilt />\n  </sitesector>\n  <sitesector>\n    <sectorid>33</sectorid>\n    <sectorname>Sector3</sectorname>\n    <clearance />\n    <azimuth />\n    <heightfromggound />\n    <mounttype />\n    <anttype />\n    <tilt />\n  </sitesector>\n</siteconfigurationinfor>

I want to convert this XML into custom type. Can anyone help me out here.
Posted
Updated 14-Dec-11 4:13am
v4

1 solution

The way I do it is like so:

C#
public class MyObject
{
    public string ID { get; set; }
    public string SiteID { get; set; }

    public XElement AsXElement
    {
        get
        {
             XElement value = new XElement("siteconfigurationinfor", 
                                           new XElement("id", ID),
                                           new XElement("id", SiteID));
             return value;
        }
        set
        {
            ID = value.Element("id").Value;
            SiteID = value.Element("siteid").Value;
        }
    }
   
    public MyObject(XElement value)
    {
        this.AsXElement = value;
    }
}


Of course, you could use the built-in serialization stuff, but I prefer to do it this way (and my actual code uses exception handling in the event of malformed XML or missing values).
 
Share this answer
 
Comments
spydeehunk 14-Dec-11 10:36am    
this is fine but i want different thing. as you can see their the list of <sitesector> tag in this xml i want to create object with list<sitesector> plz help me out. i tried to use linq as follows
XElement xdoc = new XElement(xml);

var xmlStr = from xdf in xdoc.Descendants("SiteSector")
select new SiteSectors { SectorId = Convert.ToInt32(xdf.Element("SectorId").Value), SectorName = xdf.Element("SectorName").Value };
but i am getting error that xelement could not load xml.
#realJSOP 14-Dec-11 10:47am    
The element names are case-sensitive. That's probably why it's not working for you.

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