I have an application in which I want to create an XML file.
My XML file looks something like this:
<?xml version='1.0'?>
<components>
<component name="A">
<a>1</a>
<b>1</b>
<c>
<c1>19200</c1>
<c2>8</c2>
<c3>None</c3>
<c4>1</c4>
</c>
</component>
<component name="B">
<a>1</a>
<b>1</b>
<c>
<c1>19200</c1>
<c2>8</c2>
<c3>None</c3>
<c4>1</c4>
</c>
</component>
</components>
I used the xsd.exe tool to create a class from the xml file. The class is called components.
In order to create the xml file, I entered all the data into an array, and then I wanted to enter the data into an object of type components (the class).
Here is the code I wrote:
public void CreateFile()
{
string fileName = "abc.xml"
string[] arr = new string[10];
//enter data into the array
WriteToFile(fileName, arr);
}
public void WriteToFile(string fileName, string[] data)
{
TextWriter writer;
writer = OpenFileForWrite(fileName);
XmlSerializer serializer = new XmlSerializer(typeof(components));
components comps = new components();
for (int i = 0; i < 10; i++)
{
comps.Items.name = data.name;
comps.Items.a = data.a;
comps.Items.b = data.b;
comps.Items.c[0].c1 = data.c1;
comps.Items.c[0].c2 = data.c2;
comps.Items.c[0].c3 = data.c3;
comps.Items.c[0].c4 = data.c4;
}
serializer.Serialize(writer, comps);
writer.close();
}
My problem is that there is a NullReferenceException at line:
comps.Items.name = data.name;
because comps.Items is null...
Why is this?
how can I fix it?
If there is need for further explanations - please ask..
My XML file looks something like this:
<?xml version='1.0'?>
<components>
<component name="A">
<a>1</a>
<b>1</b>
<c>
<c1>19200</c1>
<c2>8</c2>
<c3>None</c3>
<c4>1</c4>
</c>
</component>
<component name="B">
<a>1</a>
<b>1</b>
<c>
<c1>19200</c1>
<c2>8</c2>
<c3>None</c3>
<c4>1</c4>
</c>
</component>
</components>
I used the xsd.exe tool to create a class from the xml file. The class is called components.
In order to create the xml file, I entered all the data into an array, and then I wanted to enter the data into an object of type components (the class).
Here is the code I wrote:
public void CreateFile()
{
string fileName = "abc.xml"
string[] arr = new string[10];
//enter data into the array
WriteToFile(fileName, arr);
}
public void WriteToFile(string fileName, string[] data)
{
TextWriter writer;
writer = OpenFileForWrite(fileName);
XmlSerializer serializer = new XmlSerializer(typeof(components));
components comps = new components();
for (int i = 0; i < 10; i++)
{
comps.Items.name = data.name;
comps.Items.a = data.a;
comps.Items.b = data.b;
comps.Items.c[0].c1 = data.c1;
comps.Items.c[0].c2 = data.c2;
comps.Items.c[0].c3 = data.c3;
comps.Items.c[0].c4 = data.c4;
}
serializer.Serialize(writer, comps);
writer.close();
}
My problem is that there is a NullReferenceException at line:
comps.Items.name = data.name;
because comps.Items is null...
Why is this?
how can I fix it?
If there is need for further explanations - please ask..