Search code examples
xmllinq-to-sqlxelement

Convert XElement to Array


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>

Solution

  • 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();