convert xml into array?

Is there any library that will help convert xml into an array where each tag would be converted into an array item.


would be convereted into

Sure, with one caveat - you need a single root element in your XmlDocument to use System.Xml.

So add the following usings:

using System.Linq;
using System.Xml;
using System.Collections.Generic;

This routine will give you a dictionary with the keys tagA and tagB (and any others you define), the dictionary lookup is an array of the values - please note that they are all text - you can convert text values to numbers using int.Parse() and float.Parse()

    var str = @"<root><entry><tagA>1</tagA><tagB>A</tagB></entry><entry><tagA>2</tagA><tagB>B</tagB></entry></root>";
	var doc = new XmlDocument();
	var lookup = doc.DocumentElement
	    .SelectMany(c => c.ChildNodes.OfType<XmlNode>())
		.GroupBy(n => n.Name, (k,l) => new { tag = k, items = l.Select(t => t.InnerText).ToArray()})
		.ToDictionary(tag => tag.tag, tag => tag.items);

See how I’ve added a root element? You need that.

Now you have an array collection you can access like this:

var myTagAArray = lookup["tagA"];

Or you could loop through the keys, values or keys and values using a foreach().


Here is a JavaScript version:

import System.Xml;
import System.Linq;
import System.Collections.Generic;


var str = "<root><entry><tagA>1</tagA><tagB>A</tagB></entry><entry><tagA>2</tagA><tagB>B</tagB></entry></root>";
var doc = new XmlDocument();

var lookup = doc.DocumentElement
    	function(c) { 
    	return c.ChildNodes.OfType.<XmlNode>(); 
    ).GroupBy(function(n) {
    	return n.Name;
    }).Select(function(g) {
    	return { "tag": g.Key,
    	"values": g.Select(function(n){ return n.InnerText;}).ToArray() };
    }).ToDictionary(function(h) { return h["tag"];} );

var myTagAArray = lookup["tagA"]["values"];
var myTagBArray = lookup["tagB"]["values"];

Note: due to a Unity bug you have to use the second [“values”] dereference to get the array. Unity emits invalid code if you try to use the normal method that the c# version does to remove this added syntactic annoyance. For those who are interested I’ll post an explanation of the LINQ in the comments

I am not aware of a specific library that will turn each “tag” (an XML Element) into an array item but you can construct something similar yourself. Since Unity leverages Mono and Mono is an implementation of .NET, there are classes for working with XML supplied in the System.XML package… see:

Using these classes, you can parse and walk the XML document as a DOM tree and determine all the entries contained within.