Search code examples
c#xmllinqlistxelement

How to write List<int> items into an xml file?


I need to write items in the List<int> myList into an xml file. The way the xml file should look like is if the values in the list are 1, 2 and 3. I know this is possible using linq. I want to avoid the serializer options.

<List>
  <itemValue>1</itemValue>
  <itemValue>2</itemValue>
  <itemValue>3</itemValue>
</List>

Solution

  • private static void ToXml(List<int> list)
    {
        var doc = new XDocument(new XElement("List", list.Select(x =>
                              new XElement("itemValue", x))));
        doc.Save("test.xml");
    }