I am trying to read an XML file and split it so that it creates a new
file every 1000 records. I can read it, create a new one, but it
creates 1 record per file, rather than 1000. Is there a way of adding
these to the one XML file, then starting a new one when 1000 records
are reached? My code is as follows:
while (XmlReader != null && nodeCounter <= 1001)//(XmlReader != null)
{
// Create a file to write to
XmlTextWriter XmlWriter = new
XmlTextWriter(directory + "\\Output" + x + " CIS_KASN.xml",
null);//System.Text.Encoding.GetEncoding("ISO-8859-1"));
XmlWriter.Formatting = Formatting.Indented;
if (nodeCounter == 1 || nodeCounter == 1001)//%
1000 == 1)
{
XmlWriter.WriteStartDocument();
// Write the header details to the new file
//XmlWriter.WriteProcessingInstruction("xml",
"version='1.0' encoding='ISO-8859-1'");
XmlWriter.WriteComment("This XML message contains
CIS Key Accounts and Special Needs records for inserting/updating in
the IAR");
XmlWriter.WriteStartElement("message");
XmlWriter.WriteAttributeString("xmlns", "xsi",
null, "http://www.w3.org/2001/XMLSchema-instance");
XmlWriter.WriteAttributeString("xsi",
"noNamespaceSchemaLocation", null, "CISKASN.xsd");
}
// Write each row to the file, until 1000 records have
been written
//for (int i = 1; i < 1000; i++)
//{
while (XmlReader.Name != "CISKASNRecord")
{
XmlReader.Read();
}
XmlWriter.WriteNode(XmlReader, true);
XmlWriter.WriteComment("TestNode");
XmlWriter.Flush();
//}
// Tidy up and close the file so that a new one can be
opened
XmlWriter.WriteComment("TestBefore EndElement");
if (nodeCounter == 1 || nodeCounter ==
1001)//nodeCounter % 1000 == 1)
{
XmlWriter.WriteEndElement();
XmlWriter.WriteComment("TestAfter EndElement");
XmlWriter.WriteEndDocument();
}
XmlWriter.Flush();
XmlWriter.Close();
nodeCounter++;
x++;
}
Note: the commented out for-loop is how I thought I could get it to
work, but if I leave this in it creates one file, then crashes halfway
through the second saying the 'message' tag hasn't been closed. Also,
the program doesn't complete (it just hangs).
Can anybody help here please?!