B.M
B.M

Reputation: 563

One-Liner for Xml String Deserialization

Following my question on serializing a System.Array to a Xml string, I would like to ask if anyone knows of a one-line instruction to go the other way round, that is, to convert a Xml string such as

<Root><Element>a</Element><Element>b</Element></Root>

to a new string[] { "a", "b" } object. I suspect that using String.Split would be enough for the case, but it doesn't seem like the most elegant solution, does it?

Upvotes: 1

Views: 111

Answers (2)

Ray
Ray

Reputation: 46585

string test = "<Root><Element>a</Element><Element>b</Element></Root>";
var results = XElement.Parse(test).Elements("Element").Select(e => e.Value).ToArray();
  1. Parse the string
  2. Select the elements called "Element"
  3. Select the value in the elements
  4. Convert to array.
  5. (Optionally)Format it so it's one line.

Upvotes: 2

wal
wal

Reputation: 17719

How about

var data = XElement.Parse("<Root><Element>a</Element><Element>b</Element></Root>").Elements("Element").Select(e=>e.Value).ToArray();

I would advise making this more than one line for readability.

Upvotes: 3

Related Questions