How to write struct to XML file

Hello experts.

*** This is my struct: ***

public struct Coordinates
          public int x, y;

*** This is my class: ***

public class XmlClass
        public Coordinates position;


*** This is my XML file: ***

<?xml version="1.0" encoding="utf-8" ?>
<Asset Type="XmlClass" >
<position.x>9</position.x>    <- this line does not compile. How should I do it?

Thank you

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Hello Bro!

Try This.

struct MyData
   string Name;
   string Url;
   int Num;

List<MyData> myDataList;

void SaveToXml()
   XmlSerializer writer = new XmlSerializer(myDataList.GetType());
   StreamWriter file = new StreamWriter("data.xml");
   writer.Serialize(file, myDataList);

Open in new window

hope this will help you


Asif Ahmed Khan

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Hello Bro!

Below is the complete and simple code on how to serialize arrays (<=

using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

[XmlType( TypeName="State" ) ]
public class GeoEntity
 public int id;

class App
 public static void Main()
  GeoEntity[] ent = new GeoEntity[2];
  ent[0] = new GeoEntity();
  ent[0].id = 1;
  ent[1] = new GeoEntity();
  ent[1].id = 2;

  XmlTextWriter objTextWriter = null;
  XmlSerializer objSerializer = null;

  XmlRootAttribute root = new XmlRootAttribute("Results");

  objSerializer = new XmlSerializer(typeof(GeoEntity[]), root);
Stream s = new FileStream("my.xml", FileMode.Create);  
  objSerializer.Serialize( s, ent );

Open in new window

To read it back from xml file into arrays...

XmlSerializer x = new XmlSerializer(typeof(GeoEntity[]), root);
            Stream reader = new FileStream("my.xml", FileMode.Open);
            ent = (GeoEntity[])x.Deserialize(reader);

Open in new window

Hope this will help you to solve your problem.


Asif Ahmed Khan
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.