English 中文(简体)
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;
}
问题回答

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")
            });
}




相关问题
Updating Linq to XML element values concatenation issues

I am trying to write a app.config / web.config error correcting app which will audit our developers applications for incorrect environment settings. I am using Linq to XML to accomplish this and I am ...

Is LINQ to XML s XElement ordered?

When I use LINQ to XML, is the order of the elements and attributes written out to text guaranteed to be the same order as how I added the XElement and XAttribute objects? Similarly, when I read in ...

热门标签