I am trying to create nested xml elements to look like below however the created file only contains the first element from headingTags
and then the first foreach loop is exited. Why is this happening?
<?xml version="1.0"?>
<ProductProfile>
<ProfileVersion>input</ProfileVersion>
<ProductInformation>
<ApplicableProducts>input</ApplicableProducts>
<ProductDescription>input</ProductDescription>
</ProductInformation>
<CustomerInformation>
<Name>input</Name>
</CustomerInformation>
<ProductionSettings>
<LabelType>input</LabelType>
<LabelQuantity>input</LabelQuantity>
<Settings>
<SettingsSRegisters>input</SettingsSRegisters>
</Settings>
</ProductionSettings>
<PostProduction>
<ActivationStatus>input</ActivationStatus>
</PostProduction>
</ProductProfile>
This has only started happening since I added the line tw.WriteEndElement();
after the first foreach. Without this line all of the end of elements were at the end of the file.
My code:
Dictionary<string, int> tagNames = new Dictionary<string, int>()
{
{"ProfileVersion", 0},
{"ApplicableProducts", 1},
{"ProductDescription", 1},
{"Name", 2},
{"LabelType", 3},
{"LabelQuantity", 3},
{"SettingsSRegisters", 4},
{"ActivationStatus", 5}
};
public enum headingTags
{
ProductProfile, //0
ProductInformation, //1
CustomerInformation,//2
ProductionSettings, //3
Settings, //4
PostProduction //5
}
public void SaveProfile_Click(object sender, RoutedEventArgs e)
{
using (XmlTextWriter tw = new XmlTextWriter(path, Encoding.UTF8))
{
tw.Formatting = Formatting.Indented;
// Opens the document
tw.WriteStartDocument();
//tw.WriteComment("Configuration File");
foreach (int headingValue in Enum.GetValues(typeof(dataTags.headingTags)))
{
MessageBox.Show("Heading value does not match Tag name" + headingValue + " " );
string headingString = Enum.GetName(typeof(dataTags.headingTags), headingValue);
// Write heading element
tw.WriteStartElement(headingString);
tw.WriteString(txtSettingsSRegisters.Text);
foreach (KeyValuePair<string, int> dictLine in tagNames)
{
if (headingValue == dictLine.Value)
{
tw.WriteStartElement(dictLine.Key, "");
tw.WriteString("TextBoxInput");
tw.WriteEndElement();
tw.WriteWhitespace("/n");
}
else
{
//MessageBox.Show("Heading value does not match Tag name" + headingValue + " " + dictLine.Value);
}
}
//tw.WriteEndElement();
}
tw.WriteEndDocument();
// close writer
tw.Close();
}
}
UPDATE:
I added a try catch to find the exception being thrown Error:Token StartElement in state Epilog would result in an invalid XML document.
and just added this line after the foreach (int headingValue in Enum.GetValues(typeof(dataTags.headingTags)))
to implement the correct format.
if (j != 0) {
tw.WriteEndElement();
}