0

I want to make an xml file but add certain elements selectively. I would like to build those elements in memory and be able to choose whether to be written to the xml file or not. Is this possible? I'm using C# WinForms. I already looked at XmlDocument which will allow me to build an entire xml in memory but I don't want this since it's not good for large data and also takes too much memory.

2 Answers 2

2

If large data volume is your main concern, XmlWriter may be ideal. The API is perhaps not as elegant as XElement etc, but it is the most direct and efficient mechanism, and is designed for firehosing a one-way stream of data.

It has a twin, XmlReader, but that is much harder to get right - due to the complexities of processing incoming xml and accounting for child trees appropriately.

Sign up to request clarification or add additional context in comments.

4 Comments

Already checked XmlWriter, but how do I build the element and then write it to file?
@user579674 - @Ken has the answer to that. Personally I wouldn't (I'd use raw XmlWriter in this scenario), but his answer quite directly answers your question.
I have a question about XmlWriter. Do I have to use it with "using" keyword? Also, if I don't close the xml, it doesn't write anything to the file. How do I set it so it writes directly to the file than buffering?
@user579674 set AutoFlush = true, usually. Of course, unless you are writing an xml fragment (not an xml document), an incomplete xml file is not valid, as it will lack the closing tag
1

If you have a stream, named say stream, then you can create an XmlWriter by

XmlWriter.Create(stream);

Then, you can create your elements, (which are type XmlElement), and call the WriteTo method on each element you want to add, passing as an argument the XmlWriter created by XmlWriter.Create.

2 Comments

How will I create a single XmlElement? I think it is tied with XmlDocument?
Is it possible to create the xml using XmlWriter and append some elements but also create a stream and append to that some other elements and then write the stream to the XmlWriter without affecting XmlWriter's work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.