开发者

Converting array of objects to XML in C#

开发者 https://www.devze.com 2023-04-13 06:46 出处:网络
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 ano

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 X开发者_StackOverflow社区ML I have?


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>


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.

Here is a basic tutorial on serializing an Object to XML:

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号