我有以下xml文件来生成我们网站的菜单。
<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>
现在我正在使用xmlserializer将这些xml文件转换为Menu对象,并使用它们来生成菜单。我想使用LINQ to xml将这些xml文件转换为同一个对象。任何帮助将不胜感激。上面的xml文件的生成类是
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;
}
答案 0 :(得分:5)
我还没有测试过。但是,希望这有效。
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")
});
}