Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating large xml using XMLWriter in C#

Tags:

c#

xml

I was trying to create an xml which contains a large data using XMLWriter, the function has executed with out any exception.But when I opened the XML, I found that the created XML was not complete, it was broken in mid way.I dont know what I am doing wrong .Is there any default size limit for XMLWriter? Is XMLWriter the best way to create large XMLs? if not please let me know what is the best way to create large xml? Does using XDocument make my life easier?

this is my code structure (I cannot put my orginal code here !! :( )

using (//file stream)
{
     XmlWriter mywriter = new XmlWriter.Create(@"C:\mydata.xml");
       // write start element1
       // write start element2

                     while (//not end of file)
                    {
                    switch (entrytype)
                    {
                        Case 1:
                           // create elements
                        Case 2:
                           // create elements
                        so on ....
                    }
                    }

       // write end element2
       // write endelement1
}

The size of the XML is expected to be a few hundreds KB.

Please reply..

like image 873
wizzardz Avatar asked Aug 06 '26 03:08

wizzardz


1 Answers

I suspect you simply didn't close the write properly:

using (//file stream)
{
     using(XmlWriter mywriter = new XmlWriter.Create(@"C:\Auditlog.xml")) {
       // write start element1
       // write start element2

                     while (//not end of file)
                    {
                    switch (entrytype)
                    {
                        Case 1:
                           // create elements
                        Case 2:
                           // create elements
                        so on ....
                    }
                    }

       // write end element2
       // write endelement1
    }
}

Note the extra using - without that the writer may have some data still buffered. This would generally account for a missing end to the data; we obvbiously can't diagnose it exiting midway without a reproducible example.

Note also: xml will work for large files, but it isn't necessarily the best choce - a few hundred k should be fine though.

like image 192
Marc Gravell Avatar answered Aug 08 '26 17:08

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!