views:

245

answers:

1

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;
}
+4  A: 

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")
            });
}
Mehdi Golchin
Mehdi, thanks a lot. It would be great if we can find a solution that can do in single query.
raj
The problem is your Xml document structure.the first-children have a different structure with their child. if you can change the Xml document structure and make a new permanent schema for all of the menu items, it's so easy to write it in a query.
Mehdi Golchin