Reputation: 63
I have a List<Item>
collection that I am trying to generate an xml file from using Linq to XML.
The List class is below:
public class Item
{
public int Id { get; set; }
public string ItemName {get; set;}
}
I need to get XML that looks like this:
<Items>
<Item>
<ID>1</ID>
<Item_Name>Super Sale Item Name</Item_Name>
</Item>
</Items>
Here's the query I tried but am having no luck getting to work
XDocument xdoc = new XDocument(new XElement("Items"),
_myItemCollection.Select(x => new XElement("Item",
new XElement("ID", x.Id),
new XElement("Item_Name", x.ItemName))));
I keep getting an error saying it would create invalid XML. Any ideas?
Error is
This operation would create an incorrectly structured document.
at System.Xml.Linq.XDocument.ValidateDocument(XNode previous, XmlNodeType allowBefore, XmlNodeType allowAfter) at System.Xml.Linq.XDocument.ValidateNode(XNode node, XNode previous) at System.Xml.Linq.XContainer.AddNodeSkipNotify(XNode n) at System.Xml.Linq.XContainer.AddContentSkipNotify(Object content) at System.Xml.Linq.XContainer.AddContentSkipNotify(Object content) at System.Xml.Linq.XContainer.AddContentSkipNotify(Object content) at System.Xml.Linq.XDocument..ctor(Object[] content)
Upvotes: 1
Views: 973
Reputation: 4746
You're closing your first XElement too early:
XDocument doc = new XDocument(new XElement("Items",
items.Select(i => new XElement("Item",
new XElement("ID", i.Id),
new XElement("Name", i.Name)))));
Upvotes: 1
Reputation: 351648
Try this:
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);
}
}
The main thing you are missing is that the project of your collection to XElement
needs to be nested in the first XElement
("Items") rather than it's sibling. Notice that new XElement("Items")...
is changed to new XElement("Items", ...
Upvotes: 4