2009-11-14 87 views
2

我有以下xml文件来生成我们网站的菜单。如何使用LINQ将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

这将是更容易,如果我们能看到实际的XML的菜单,而不是对同一模式定义。 – Murph 2009-11-14 12:20:20

+1

为什么要使用Linq-to-XML而不是直接反序列化它们?将XML反序列化为对象看起来好像是更容易和更好的方式来做到这一点.... – 2009-11-14 13:11:15

+0

这就是我现在正在做的事情。我只是有兴趣知道如何将递归XML转换为使用LINQ的对象集合。 – raj 2009-11-14 14:43:07

回答

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

Mehdi,非常感谢。如果我们能够找到可以在单个查询中执行的解决方案,那将是非常好的。 – raj 2009-11-14 14:51:08

+0

问题在于你的Xml文档结构。第一个孩子与他们的孩子有不同的结构。如果您可以更改Xml文档结构并为所有菜单项创建新的永久架构,那么将其写入查询非常容易。 – 2009-11-14 19:13:27