I know there's no built in converter to convert an array of objects to XML. Is there a quick rudimentary way to create a XML out of the array to help me do a LINQ to XML join between this one and another XML I have?
Asked
Active
Viewed 2.8k times
11
-
Do you mean besides just writing a list of tag/value pairs to a text file? – mbeckish Oct 14 '11 at 17:56
-
You may not have to convert the objects to XML; that's not a requirement for doing joins when you use LINQ to XML. You should provide more details, like what type of query you're trying to write and what the class looks like for your objects. – Jacob Oct 14 '11 at 17:56
2 Answers
17
You can use Linq to XML, it is really easy to map from your existing data structures to XML, i.e.:
int[] values = { 1, 2, 17, 8 };
XDocument doc = new XDocument();
doc.Add(new XElement("root", values.Select( x=> new XElement("item", x))));
produces the following output:
<root>
<item>1</item>
<item>2</item>
<item>17</item>
<item>8</item>
</root>

BrokenGlass
- 158,293
- 28
- 286
- 335
-
1Neat! Is there any way we could do the same for a multidimensional array? For `string[,] values` – slayernoah Nov 17 '15 at 01:35
4
You can always use XmlSerializer
to transform a list of C# objects to XML document. The result of the serialization may be customized by using metadata attributes to designate, for example, root nodes or which class property is to be ignored etc... You will definitely need to apply the attributes to make the resulting XML conform as much as possible to your requirements.

Anas Karkoukli
- 1,342
- 8
- 13
-
Also refer to this post for a lot of examples of serializing a list of objects http://stackoverflow.com/questions/1212742/xml-serialize-generic-list-of-serializable-objects – Nathan Anderson Oct 14 '11 at 17:54
-