XMLDocument Load method not releasing memory

In my C# application, I have class which has method that opens an XML 
document, modifies it and saves it out.  I run that method for several 
different XML documents.  What I've found is that the Load emthod on the 
MXLDocument isntance loads the document into memory (as it should) but I 
have no way of releaseing that memory throughout the application, and I 
run out of memory.  The  documents I'm loading are abou 10 MB in size, 
and I run out of memory before 50 of them are loaded.
Here's the code for the method:
public void Clean(string strCleanXMLPath)
{
	XmlDocument xmlDoc = new XmlDocument();

	xmlDoc.Load(strCleanXMLPath);

	//do some work here on the xmlDoc			

	XmlTextWriter wrtr = new XmlTextWriter(strCleanXMLPathEncoding.UTF8);
	wrtr.Formatting = Formatting.Indented;
	xmlDoc.WriteTo(wrtr);
	wrtr.Close();
	xmlDoc = null;		
}

How do I get it to release the memory?
thanks!

0
5/7/2004 7:28:50 PM
dotnet.xml 7266 articles. 0 followers. Follow

11 Replies
1554 Views

Similar Articles

[PageSpeed] 26

Hi

First of all, I would like to confirm my understanding of your issue. From 
your description, I understand that memory of the XmlDocument was not 
released after using in your app. If there is any misunderstanding, please 
feel free to let me know.

As far as I know, the memory has to be released automatically when the 
object reference is out of scope. The Garbage Collection of .NET 
framework's CLR will do this for us. If the memeory is not released, please 
try to use the using statement in C#, so that we can make sure that the 
memeory is enforced to be released when out of scope. Here is an example:

	public void Clean(string strCleanXMLPath)
	{
		using(XmlDocument xmlDoc = new XmlDocument())
		{
			xmlDoc.Load(strCleanXMLPath);

			//do some work here on the xmlDoc			

			XmlTextWriter wrtr = new XmlTextWriter(strCleanXMLPathEncoding.UTF8);
			wrtr.Formatting = Formatting.Indented;
			xmlDoc.WriteTo(wrtr);
			wrtr.Close();
			xmlDoc = null;		
		}
	}


HTH. If anything is unclear, please feel free to reply to the post.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no 
rights."

0
v-kevy (347)
5/8/2004 2:48:48 AM
Matthew Wieder wrote:

>     xmlDoc = null;       
> }
> 
> How do I get it to release the memory?

Well, basically GC should take care if it's out of scope or nulled. Make 
sure you don't have some live reference to the XmlDocument or its nodes 
elsewhere. You can try some .NET profiler tool too.
-- 
Oleg Tkachenko [XML MVP]
http://blog.tkachenko.com
0
Oleg
5/9/2004 8:01:02 AM
When I attempt to compile the code you suggested, I get the error that 
"Cannot implicitly convert type 'System.Xml.XmlDocument' to 
'System.IDisposable'"  If XmlDocument does not implement IDisposable, 
then perhaps there is a larger issue here that the XmlDocument never 
goes out of scope?
thanks,
-Matthew

Kevin Yu [MSFT] wrote:
> Hi
> 
> First of all, I would like to confirm my understanding of your issue. From 
> your description, I understand that memory of the XmlDocument was not 
> released after using in your app. If there is any misunderstanding, please 
> feel free to let me know.
> 
> As far as I know, the memory has to be released automatically when the 
> object reference is out of scope. The Garbage Collection of .NET 
> framework's CLR will do this for us. If the memeory is not released, please 
> try to use the using statement in C#, so that we can make sure that the 
> memeory is enforced to be released when out of scope. Here is an example:
> 
> 	public void Clean(string strCleanXMLPath)
> 	{
> 		using(XmlDocument xmlDoc = new XmlDocument())
> 		{
> 			xmlDoc.Load(strCleanXMLPath);
> 
> 			//do some work here on the xmlDoc			
> 
> 			XmlTextWriter wrtr = new XmlTextWriter(strCleanXMLPathEncoding.UTF8);
> 			wrtr.Formatting = Formatting.Indented;
> 			xmlDoc.WriteTo(wrtr);
> 			wrtr.Close();
> 			xmlDoc = null;		
> 		}
> 	}
> 
> 
> HTH. If anything is unclear, please feel free to reply to the post.
> 
> Kevin Yu
> =======
> "This posting is provided "AS IS" with no warranties, and confers no 
> rights."
> 

0
5/10/2004 1:20:12 PM
Any variable goes out of scope if you don't keep references to it (for
example in some global cache).
IDisposable is not implemented in the XmlDocument as its resources are pure
..NET object and references that are automatically freed by the garbage
collector.
You don't even need to set it to null before exiting the method.
Can you show us the full code that "leaks"?

-- 
Daniel Cazzulino [MVP XML]
Clarius Consulting SA
http://weblogs.asp.net/cazzu
http://aspnet2.com
"Matthew Wieder" <Development@SatoriGroupInc.com> wrote in message
news:uo08oEpNEHA.4036@TK2MSFTNGP12.phx.gbl...
> When I attempt to compile the code you suggested, I get the error that
> "Cannot implicitly convert type 'System.Xml.XmlDocument' to
> 'System.IDisposable'"  If XmlDocument does not implement IDisposable,
> then perhaps there is a larger issue here that the XmlDocument never
> goes out of scope?
> thanks,
> -Matthew
>
> Kevin Yu [MSFT] wrote:
> > Hi
> >
> > First of all, I would like to confirm my understanding of your issue.
From
> > your description, I understand that memory of the XmlDocument was not
> > released after using in your app. If there is any misunderstanding,
please
> > feel free to let me know.
> >
> > As far as I know, the memory has to be released automatically when the
> > object reference is out of scope. The Garbage Collection of .NET
> > framework's CLR will do this for us. If the memeory is not released,
please
> > try to use the using statement in C#, so that we can make sure that the
> > memeory is enforced to be released when out of scope. Here is an
example:
> >
> > public void Clean(string strCleanXMLPath)
> > {
> > using(XmlDocument xmlDoc = new XmlDocument())
> > {
> > xmlDoc.Load(strCleanXMLPath);
> >
> > //do some work here on the xmlDoc
> >
> > XmlTextWriter wrtr = new XmlTextWriter(strCleanXMLPathEncoding.UTF8);
> > wrtr.Formatting = Formatting.Indented;
> > xmlDoc.WriteTo(wrtr);
> > wrtr.Close();
> > xmlDoc = null;
> > }
> > }
> >
> >
> > HTH. If anything is unclear, please feel free to reply to the post.
> >
> > Kevin Yu
> > =======
> > "This posting is provided "AS IS" with no warranties, and confers no
> > rights."
> >
>


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.679 / Virus Database: 441 - Release Date: 07/05/2004


0
kzuAT4605 (35)
5/10/2004 9:15:46 PM
I provided the code in my original post.  Just call that method 100 
times with a 10 MB xml file and watch the memory grow.

Daniel Cazzulino [MVP XML] wrote:
> Any variable goes out of scope if you don't keep references to it (for
> example in some global cache).
> IDisposable is not implemented in the XmlDocument as its resources are pure
> .NET object and references that are automatically freed by the garbage
> collector.
> You don't even need to set it to null before exiting the method.
> Can you show us the full code that "leaks"?
> 

0
5/11/2004 1:09:33 PM
Just to confirm it's an issue on my end, please run with an xml file 
over 10 MB.
thanks!

Oleg Tkachenko [MVP] wrote:

> Matthew Wieder wrote:
> 
>> I provided the code in my original post.  Just call that method 100 
>> times with a 10 MB xml file and watch the memory grow.
> 
> 
> Well, I just run that code 100 times with 4 Mb xml file under really 
> heavy load. No memory problems. In fact I'd be surprised to see memory 
> leak in such simple and common code.
> You may want to try some .NET profiler to see what's going on (there are 
> lots of such tools available including freeware, e.g. take a look at 
> http://download.microsoft.com/download/4/4/2/442d67c7-a1c1-4884-9715-803a7b485b82/clr%20profiler.exe). 
> 

0
5/11/2004 5:27:28 PM
Matthew Wieder wrote:
> I provided the code in my original post.  Just call that method 100 
> times with a 10 MB xml file and watch the memory grow.

Well, I just run that code 100 times with 4 Mb xml file under really 
heavy load. No memory problems. In fact I'd be surprised to see memory 
leak in such simple and common code.
You may want to try some .NET profiler to see what's going on (there are 
lots of such tools available including freeware, e.g. take a look at 
http://download.microsoft.com/download/4/4/2/442d67c7-a1c1-4884-9715-803a7b485b82/clr%20profiler.exe).
-- 
Oleg Tkachenko [XML MVP]
http://blog.tkachenko.com
0
Oleg
5/11/2004 6:12:32 PM
Here (http://aspnet2.com/kzu/weblog/verano.zip) you have a real 150Mb XML
file compressed in 6Mb. I use it for testing all the time.

-- 
Daniel Cazzulino [MVP XML]
Clarius Consulting SA
http://weblogs.asp.net/cazzu
http://aspnet2.com

"Matthew Wieder" <Development@SatoriGroupInc.com> wrote in message
news:#MqFdz3NEHA.664@TK2MSFTNGP09.phx.gbl...
> Just to confirm it's an issue on my end, please run with an xml file
> over 10 MB.
> thanks!
>
> Oleg Tkachenko [MVP] wrote:
>
> > Matthew Wieder wrote:
> >
> >> I provided the code in my original post.  Just call that method 100
> >> times with a 10 MB xml file and watch the memory grow.
> >
> >
> > Well, I just run that code 100 times with 4 Mb xml file under really
> > heavy load. No memory problems. In fact I'd be surprised to see memory
> > leak in such simple and common code.
> > You may want to try some .NET profiler to see what's going on (there are
> > lots of such tools available including freeware, e.g. take a look at
> >
http://download.microsoft.com/download/4/4/2/442d67c7-a1c1-4884-9715-803a7b485b82/clr%20profiler.exe).
> >
>


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.679 / Virus Database: 441 - Release Date: 08/05/2004


0
kzuAT4605 (35)
5/11/2004 8:16:34 PM
Hi Matthew,

I have tried the 155Mb Xml file that Oleg has provided on my machine. 
However, I cannot repro this issue. So I think this might be machine 
specific.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no 
rights."

0
v-kevy (347)
5/12/2004 6:11:26 AM
I am also having a similar problem.  My memory accumulates and does not
get garbage collected.  If I add System.GC.Collect() though, my memory
accumulation stops.  This does not seem right though.  If anyone has any
help, it is greated appreciated.

Thanks! (kit_mx1@hotmail.com)


*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
0
kit_mx1 (1)
6/16/2004 10:04:54 PM
Kay Dee wrote:

> I am also having a similar problem.  My memory accumulates and does not
> get garbage collected.  If I add System.GC.Collect() though, my memory
> accumulation stops.  This does not seem right though. 

That's how GC works. The collection process doesn't run if you have 
enough memory available.

-- 
Oleg Tkachenko [XML MVP]
http://blog.tkachenko.com
0
Oleg
6/17/2004 8:43:03 AM
Reply:

Similar Artilces:

Error 48 Error in Loading DLL
I'm running Windows 2000 and Outlook 2002 I have some simple test code which runs ok on machines with Windows 2000 and Outlook 2000 but not on my version as mentioned above. I've tried using. Outlook 2002 "Microsoft Outlook 10.0 Object Library" msoutl.olb and "Microsoft Outlook 9.0 Object Library" neither work sample code.......... ---------------------------------- Private Sub Command1_Click() Dim objOutlook As New Outlook.Application Dim objMail As MailItem Set objOutlook = CreateObject("outlook.application") Set objMail = objOutlook.CreateItem(ol...

Shared memory
Hi, Where is shared memory allocated when CreateFileMapping / MapViewOfFile is used? Obviously it should not be in the address space of any process using it. Is it in some kind of surrogate process address space? TIA, SD No, it can ONLY be in the address space of the processes that are using it! Otherwise, they could not use it! That's where it is allocated: in the address space of each of the processes that use it. Note that it does not have to be in the *same address* in each of the processes! This means you cannot store pointers in it, unless you used __based pointers. joe ...

XMLWriter and XMLDocument
Okay I am using an XMLDocument object to process several thousands of lodgements (from a database) I am trying to output it from an XML Document to a file using the XmlDocument.WriteTo() method with an XmlWriter. It writes 131kB and then cuts out halfway through an element Is this a limitation of XmlDocument.WriteTo() ? What would be a better way to output it Thanks Ensure you're calling XmlWriter.Close() to cause the buffered writes to be flushed to the underlying stream/textwriter. -- Daniel Cazzulino [MVP XML] Clarius Consulting SA http://weblogs.asp.net/cazzu http://aspnet2.com ...

Preventing HTML graphics from automatically loading in preview pane
I'm wondering if anyone knows how to prevent outlook from automatically loading images in the preview pane. A lot of spammer's deliberately include html graphics in their messages. The URL for a particular image in the message is unique to the user it is sent to. When outlook displays such an image in the preview pane, it is essentially telling the spammer "Hey there spammer, here's a confirmation that I, <insert your e-mail address here> got your junk mail." Such confirmations tend to increase the quantity of junk mail a user receives. Even webmail client...

Performance Optimizer and Memory Allocation
Hi, We're running 5.5 and the store is using a huge ammount of memory which doesn't leave much after the other processes take their share. We recently moved our server to a DMZ and when backups run from the Lan to the DMZ to backup exchange the server freezes and generates a virtual memory error. Can we\should we use performance optimizer to allocate memory for the information store? Do you think this would solve our problem? Available memory before backups run was 200 megs an hour ago and is now 80 and dropping. Our other server is at 9 megs. Thanks for any help you c...

Load Data Under Column Headings
My data are stock prices that I want to use with Metastock. I have as column headers: Date, Stock Name, Open, High, Low, Close, Stock Code. How do I load stock data with their fields under the respective column headings, perhaps, by just clicking on the file name, without using cut & paste. How do I protect the heading row from being overwritten? ...

Workbook loads but does not display
This is a weird one. Excel 2003 SP2 running on XP Pro SP2 in a SBS 2003 SP1 environment. If Excel is closed and you double-click on an Excel document, the workbook does not display. There is just a big, empty grey window. Status bar says "Done" and there are no error messages. If you minimize/maximise Excel or click on the New Document button, the document then displays fine. Any ideas, anyone? TIA, Bill Bill Couple of things 1) Look at Tools>Options...>General>Ignore other applications - Uncheck 2) Search (hidden files also) for a file called *.xlb (This is a ...

XmlDocument with URL
My goal is to load an xml document from a remote url, make some changes to it, and then display it in a webpage. Say my codebehind looks like this private void Page_Load(Object sender, EventArgs e) { XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8); XmlDocument doc = new XmlDocument(); doc.Load(http://somexmlgeneratedhere.com?id=333); //manipulate the doc here doc.WriteTo(writer); } Im not getting the full document from the URL, I'm sure Im doing this wrong. Can anyone point me in the right direction? thanks in advance Dave He...

NK2csv v.06 beta is released
NK2csv is a free utility that allows you to view and edit the contents of your Outlook autocompletion cache stored in a NK2 file. Using the utility you may then export to CSV format and import into your Outlook contacts. It is important to note that this project is still in beta until version 1.0 is finally released. The project website is: http://www.epute.com/nk2csv/ Current change log follows. Version .06 beta released 1/15/06 7:15PM Features Added - Added name address Add and Remove - Group by Domain - New and improved help menu Bug Fixes - Fixed Browse button causing runtime error 5 w...

Internal problem on XmlDocument.Load( )
I have this really frustrating problem when calling XmlDocument.Load(string filename). Whenever I call this method in a web application in my Windows XP development PC, I get the following error: Specified argument was out of the range of valid values. Parameter name: The specified value must be greater than 0. Here's the stack trace: ------------------------- [ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: The specified value must be greater than 0.] System.Net.ServicePoint.set_ConnectionLimit(Int32 value) +60 System.Xml.XmlDo...

XSLT transform XmlDocument to XmlDocument?
I just want to make a transformation on the fly, without having to save the XML document to a file before or after the transformation. I don't find any examples of this. I see that the XslTranform.Transform() method can return an XmlReader, but how can that reader be converted to an XmlDocument object? Big thanks, Gustaf Gustaf Liljegren wrote: > I just want to make a transformation on the fly, without having to save > the XML document to a file before or after the transformation. I don't > find any examples of this. See <http://groups-beta.google.com/group/mic...

Detecting Memory Leaks
At one time, the debug build would always report any memory leaks in the output window when my application terminated. Now, I'm finding it does not. (I deliberately wrote code to leak memory and nothing was reported.) I found the following link, which describes how to detect memory leaks. But did this change or something? I didn't have to do this before. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/html/_core_detecting_a_memory_leak.asp Thanks. -- Jonathan Wood SoftCircuits Programming http://www.softcircuits.com Which version of VS are you usin...

Error Loading Outlook CRM Client (Tried other solutions)
Ok maybe someone can point me to the right place to look for an answer. I have a client PC that gets the following everytime he opens Outlook. "An error occurred loading Microsoft CRM functionality. Try restarting Microsoft Outlook. Contact your system administrator if errors persist." He is using a Desktop that the previous user was able to use just fine with CRM and Outlook and in fact the rest of my office has no problem with this add-in just this one user. We removed other Logins (there wern't any) We changed the RCOffline to "1" We changed his trusted sit...

XPathDocument to xmldocument
How to create XPathDocument object from xmldocument object thanks vikram wrote: > How to create XPathDocument object from xmldocument object First, be aware that such converting means copying the whole set of data in the XML document. Second, it's easy: XPathDocument doc = new XPathDocument(new XmlNodeReader(xmlDoc)); -- Oleg Tkachenko [XML MVP, MCP] http://blog.tkachenko.com ...

Loading XmlDocument with a file on network?
Can you load an XmlDocument with a file located on a network share? I thought maybe the XmlResolver could be used XmlUrlResolver resolver = new XmlUrlResolver() resolver.Credentials = CredentialCache.DefaultCredentials // Create and load the XmlDocument XmlDocument doc = new XmlDocument() doc.XmlResolver = resolver; // Set the resolver doc.Load(@"\\devsrv\profiles\0004.xml") OR.. doc.Load("//devsrv/profiles/0004.xml") But I get: "Logon failure: unknown user name or bad password" The problem is probably that the account that your application is running under...

removing nodes from xmldocument
Here is an xml structure. i want to remove <a> nodes that do not have any child. How can i do that in csharp? <root> <a> <b/> </a> <a/> <a/> <a> <c/> </a> </root> i tried following but it does not work: xmlNodeList l = xr.getElementsByTagName("a"); foreach(XmlNode n in l) { if(n.HasChildNodes == false) xr.RemoveChild(n) } emid, Try this call this function inside the code; void RecurssionRemoval() { XmlNodeList l = xr.GetElementsByTagName("a"); ...

outPutTo method
I am using above method with success. The .rtf file is generated, however the formatting is lost. i.e the tabular latyout of text in the Access report is not maintained in the .rtf. How can I over come this issue? -- Learning SQL and Access On Jul 9, 7:04 am, stephenson22 <stephenso...@discussions.microsoft.com> wrote: > I am using above method with success. > > The .rtf file is generated, however the formatting is lost. i.e the tabular > latyout of text in the Access report is not maintained in the .rtf. > > How can I over come this issue? > -- > Learning SQ...

Slow Loading Of Calendar
Although Outlook 2007 is a bit slow in loading my Inbox initially my main concern is that when I move from Mail to Calendar it is very slow in loading. It can take up to 30 seconds to load my calendar view. Once Outlook is loaded I have no problemas in movng between Inbox and Contacts, but Calendar is slow. So far I have reduced my Addins to the bare minimum and deleted calendar entries before 2009. Most of my entries are recurring entries and, to be honest, there is not very much in the Calendar at all which is what puzzles me. Anyone any ideas. -- Gareth ...

E2K3 Memory Loss
We have a clustered pair of Exch 2003 servers (active\passive) running on Win2003 Enterprise Server. Hardware = HP DL380, G3, dual 3.0 ghz. proc. with 4 gig. of memory. The environment ~ 400 users. We have a duplicate set up at another site. The servers with that own the cluster resources use more and more memory, until we receive low memory warnings at the end of the week...requiring us to fail over the cluster and reboot the server....which ends up taking a long time. Any ideas on correcting? Issue occurs at both sites. Thx. You should consider running the best practice analyzer...

Loading CSV and Special character
Hi, i was wandering if i was able to put an ascii character in a CSV file to be able to force a page-break in Excel when i load the file. Been trying Ascii character 11 and 10. But none are working! Is that doable? Or should i output a formula/Excel command (which i dont know) to do it? Thanks guys! ...

Update Index Method in Subform
I have a form with several subforms on it. Because the table relationships are required to be a certain way, I have had to code in a method for synching the records via the form. The code is below: Private Sub Form_Current() Dim Response As Variant On Error Resume Next If IsNull(Me.INVNUM) Then Me.INVNUM = Format(DMax("Left([INVNUM],5)", "HDRPLAT") + 1, "00000") & "A" Response = MsgBox("Is this Invoice Number what you want?", vbOKCancel) If Response = vbCancel Then Me.Undo Exit Sub End If Response = acDataErrC...

ANN: xsdbXML release with C#/.NET port
ANN: xsdbXML release with C#/.NET port Part I: Announcement ==================== There is a new release of xsdbXML which provides bugfixes to the Python implementation and also provides a completely separate implementation in C#/.NET. The xsdb framework provides a flexible and well defined infrastructure to allow tabular data to be published, retrieved, and combined over the Internet. Read more and download at http://xsdb.sourceforge.net Part II: Discussion =================== The C# implementation is primarily a transliteration of the Python implementation. I hope to also do a java tr...

Outlook 2002 Crash on "Big Memory" System
This is a multi-part message in MIME format. ------=_NextPart_000_0008_01C44FD9.D8DDF960 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I've run Outlook 2002 since it came out, but recently encountered an = exasperaing problem when I installed it on my new system (Abit IC7-MAX3 = motherboard, P4-3.0, 1 GB RAM) which has two users (both = administrators). If one user runs Outlook, then when the second user runs it, it crashes = with the error message labelled, "Microsoft Visual C++ Runtime Library", = and stating, "Run...

Resource Load -
Hi there Can anyone help? I have a single master plan with a number of different projects in it. The same resources are working on all the projects. In the resource usage view I want see how many days each resource is working on a particular project on a monthly basis. So for example I want to see: HR May June July Joe Bloggs 15d 10d 12d Marketing May June July Joe Bloggs 5d 3d 4d In the Gantt chart view I added a text1 field with the project name and then tried to filter it in the resource usage view but it doesn�t display in the resourc...

.NET XMLDocument Save issue
Hi, Currently we are using the .NET XMLDocument Class to manipulate some xml documents. The issue we are having is that when we save the XML files using the classes save method, empty xml tags will be saved with a CRLF instead of the empty value. This can be solved by setting the PreserveWhiteSpace property to true. But then the indentation is lost. E.g.:- Before Saving this is how the tags are. <Test></Test> After saving <Test> </Test> Has anybody come across this, is there any solution for this. Thanks Amendra. ...