I am trying to read an XML file and break it up into smaller chunks but am having real problems in doing so as I have never used XML (and am new to C#), so would appreciate any help possible.
then wish to read a large XML document and cycle through it, copying each record to a new file that I have created (with the above header info), until I have 1000 records, then start again. The format of the records is:
<Record>
<attribute1>blah blah</attribute1>
<attribute2>blah blah</attribute2>
<attribute3>blah blah</attribute3>
</Record>
So far I have created the following code:
while (fileReader != null)
{
// Create a file to write to
XmlTextWriter fileWriter = new XmlTextWriter(directory + "\\Output" + x + " myFile.xml", System.Text.Encoding.GetEncoding("ISO-8859-1"));//null);//System.Text.Encoding.UTF8);
// Write the header details to the new file
fileWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='ISO-8859-1'");
fileWriter.WriteStartElement("!-- My comments go here --");
fileWriter.WriteStartElement("message");
fileWriter.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
fileWriter.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, "myXSDdoc.xsd");
// Add 'messageHeader' as the element to enclose records in the file
while (fileReader.Name != "messageHeader")
{
fileReader.Read();
}
fileWriter.WriteNode(fileReader, true);
// Write each row to the file, until 1000 records have been written
for (int i = 1; i <= 1001; i++)
{
while (fileReader.Name != "KeyRecord")
fileReader.Read();
fileWriter.WriteNode(fileReader, true);
fileWriter.Flush();
}
// Tidy up and close the file so that a new one can be opened
fileWriter.WriteEndElement();
fileWriter.Close();
x++;
}
I can create a new XML file which prints the header info, then begins to cycle through and print the records as expected (hoped!). However, it crashes at the end with the following error:
"A name was started with an invalid character. Error processing resource 'file:///C:/..."
Also, the second file is created but cannot even be displayed, as it shows the following error:
"XML document must have a top level element. Error processing resource 'file:///C:/..."
Can anybody help please?!