raj
raj

Reputation: 265

How to use LINQ to convert a xml file in to an object

I have xml files with following to generate the menu for our web site.

 <xs:element name="Menu">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="MenuItem" type="MenuItemType" maxOccurs="unbounded"></xs:element>
        </xs:sequence>
        <xs:attribute name="Title" type="xs:string"></xs:attribute>
        <xs:attribute name="Type" type="xs:string"></xs:attribute>
    </xs:complexType>

</xs:element>
<xs:complexType name="MenuItemType">
    <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="MenuItem" type="MenuItemType" />
    </xs:choice>
    <xs:attribute name="Text" type="xs:string"></xs:attribute>
    <xs:attribute name="Url" type="xs:string"></xs:attribute>
</xs:complexType>

Right now I am using xmlserializer to convert these xml files in to Menu objects and use them to generate the menu. I want to use LINQ to xml to convert these xml files in to same object. Any help will be appreciated. Generated class for above xml file is

 public partial class Menu {

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("MenuItem")]
    public MenuItemType[] MenuItem;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Title;
    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Type;
}
public partial class MenuItemType {

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("MenuItem")]
    public MenuItemType[] Items;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Text;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Url;
}

Upvotes: 2

Views: 2376

Answers (1)

m3kh
m3kh

Reputation: 7941

I haven't tested it. But, hope this works.

var o = (from e in XDocument.Load("").Elements("MenuItem")
         select new Menu
         {
             MenuItem = GenerateMenuItemType(e).ToArray(),
             Title = (string)e.Attribute("Title"),
             Type = (string)e.Attribute("Type")
         });

private IEnumerable<MenuItemType> GenerateMenuItemType(XElement element)
{
    return (from e in element.Elements("MenuItem")
            select new MenuItemType
            {
                Items = GenerateMenuItemType(e).ToArray(),
                Text = (string)e.Attribute("Title"),
                Url = (string)e.Attribute("Url")
            });
}

Upvotes: 5

Related Questions