2010-12-08 143 views
1

我有一个List<Item>集合,我试图从Linq到XML生成一个xml文件。Linq to XML查询问题

List类低于:

public class Item 
{ 
    public int Id { get; set; } 
    public string ItemName {get; set;} 
} 

我需要XML,看起来像这样:

<Items> 
    <Item> 
    <ID>1</ID> 
    <Item_Name>Super Sale Item Name</Item_Name> 
    </Item> 
</Items> 

这是我试过的查询,但我有没有运气往返于工作

XDocument xdoc = new XDocument(new XElement("Items"), 
      _myItemCollection.Select(x => new XElement("Item", 
              new XElement("ID", x.Id), 
              new XElement("Item_Name", x.ItemName)))); 

我不断收到一个错误,说它会创建无效的XML。有任何想法吗?

错误是

此操作会创建一个结构错误的文档。

在System.Xml.Linq.XDocument.ValidateDocument(XNode以前,XmlNodeType allowBefore,XmlNodeType allowAfter) 在System.Xml.Linq.XDocument.ValidateNode(XNode节点,XNode先前) 在System.Xml.Linq的。 XContainer.AddNodeSkipNotify(XNode N) 在System.Xml.Linq.XContainer.AddContentSkipNotify(对象内容) 在System.Xml.Linq.XContainer.AddContentSkipNotify(对象内容) 在System.Xml.Linq.XContainer.AddContentSkipNotify(对象内容) at System.Xml.Linq.XDocument..ctor(Object [] content)

+0

你可以复制/粘贴你有确切的错误? – 2010-12-08 04:58:20

+0

我在那里添加了,没有更多。 – John 2010-12-08 05:03:06

回答

4

试试这个:

using System; 
using System.Linq; 
using System.Xml.Linq; 

public class Item 
{ 
    public int Id { get; set; } 
    public string ItemName { get; set; } 
} 

class Program 
{ 
    static void Main() 
    { 
     var collection = new[] 
     { 
      new Item {Id = 1, ItemName = "Super Sale Item Name"} 
     }; 

     var xdoc = new XDocument(new XElement("Items", 
           collection.Select(x => new XElement("Item", 
             new XElement("ID", x.Id), 
             new XElement("Item_Name", x.ItemName))))); 

     Console.WriteLine(xdoc); 
    } 
} 

您缺少的主要原因是您收集的项目需要嵌套在第一个XElement(“项目”)中,而不是它的兄弟。请注意,new XElement("Items")...改为new XElement("Items", ...

1

你关闭你的第一个的XElement太早:

XDocument doc = new XDocument(new XElement("Items", 
      items.Select(i => new XElement("Item", 
           new XElement("ID", i.Id), 
           new XElement("Name", i.Name)))));