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)
Try this:
The main thing you are missing is that the project of your collection to
XElementneeds to be nested in the firstXElement(“Items”) rather than it’s sibling. Notice thatnew XElement("Items")...is changed tonew XElement("Items", ...