The whole point of your problem is building the best algorithm to extract the DB information in the most efficient way. In principle, it seems better to rely on XmlWriter
, but with the proper algorithm other alternatives might also be OK.
Sample code:
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.NewLineOnAttributes = false;
settings.Indent = true;
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("output.xml", settings))
{
writer.WriteStartDocument();
int[] IS_CONTAINER = new int[] { 1, 1, 0, 0, 1, 1 };
string[] TAG_NAME = new string[]{ "x", "y", "a", "b", "/y", "/x"};
string[] TAG_VALUE = new string[]{ null, null, "cc", "kk", "/y", "/x"};
for (int i = 0; i <= TAG_NAME.Length - 1; i++)
{
if (!TAG_NAME[i].Contains("/"))
{
writer.WriteStartElement(TAG_NAME[i]);
if(TAG_VALUE[i] != null) writer.WriteValue(TAG_VALUE[i]);
}
if(IS_CONTAINER[i] == 0 || TAG_NAME.Contains("/")) writer.WriteEndElement();
}
writer.WriteEndDocument();
}
Note that this algorithm assumes that the DB information is always right and thus does not need to keep track of opened nodes (whenever a closing tag appears a node has to be closed because it is certainly opened). In case of not wanting to trust the correctness of the DB information blindly, you would have to keep track of opened tags.