fgblomqvist
fgblomqvist

Reputation: 2424

Get XElement.Value on multiple elements by element name

I have this code:

XDocument xdoc = XDocument.Parse(xml);
XElement xe = xdoc.Root.Element("program");

string[] data = new string[3];

XElement element = xe.Element("name");
data[0] = element.Value;

element = xe.Element("version");
data[1] = element.Value;

element = xe.Element("beta");
data[2] = element.Value;

return data;

Is it possible to write something like this instead:

xe.Element["name"].Value
xe.Element["version"].Value

I know I can't write exactly like that, but is their any method that works like that one? So that I get rid of some lines and makes the process faster.

Upvotes: 0

Views: 1550

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500525

Yes, just use the right kind of brackets, for the method call instead of indexer syntax...

return new string[] {
    xe.Element("name").Value,
    xe.Element("version").Value,
    xe.Element("beta").Value
};

Upvotes: 1

Related Questions