0

How should i convert XElement like below into an array of Points (Point could be a class with variables X and Y):

<Points xmlns="">
  <Point X="420" Y="240" />
  <Point X="400" Y="298" />
  <Point X="350" Y="335" />
  <Point X="289" Y="335" />
  <Point X="239" Y="298" />
  <Point X="220" Y="239" />
  <Point X="239" Y="181" />
  <Point X="289" Y="144" />
  <Point X="350" Y="144" />
  <Point X="400" Y="181" />
</Points>
Masood Alam
  • 645
  • 2
  • 8
  • 22

2 Answers2

3

This worked for me, was able to get an array from the xe XElement. (there could be a better way though)

Point[] points = (from pt in xe.Elements("Point")
                    let x = Convert.ToInt32(pt.Attribute("X").Value)
                    let y = Convert.ToInt32(pt.Attribute("Y").Value)
                    select new Point(x, y)).ToArray();
Masood Alam
  • 645
  • 2
  • 8
  • 22
1

You can simply type-cast XAttribute to int :

Point[] points = (from pt in xe.Elements("Point")
                  let x = (int)pt.Attribute("X")
                  let y = (int)pt.Attribute("Y")
                  select new Point(x, y)).ToArray();

This way exception won't be thrown in case the attribute not found in current element, not to mention it's shorter. Or if you prefer method syntax :

Point[] points = xe.Elements("Point")
                   .Select(p => new Point((int)p.Attribute("X"), (int)p.Attribute("Y")))
                   .ToArray();
har07
  • 88,338
  • 12
  • 84
  • 137