![]() |
Languages »
C / C++ Language »
General
Intermediate
Simplify Reading and Writing of XML FragmentsBy notmasteryetThis article shows how to read and write XML fragments using the XmlChunkReader and XmlChunkWriter classes. |
XML, C# 2.0, Windows, .NET 2.0, Visual Studio, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
This article is trying to solve two ultimate serialization problems:
XmlReader processes;
XmlWriter processes. Solving these problems makes the using of XmlSerializer possible when you are creating XML from objects.
The library contains two classes: XmlChunkReader and XmlChunkWriter.
XmlChunkReader can be created using XmlReader while it�s reading XML element nodes. It can be used as a standalone XmlReader, e.g., to perform a deserialization operation. When XmlChunkReader is closed, the main reader points to the next XML node. Using XmlChunkReader helps avoid such calls as ReadInnerXml.
// read file
using (XmlTextReader r = new XmlTextReader(xmlfile))
{
r.ReadStartElement("items");
while (r.Read() && r.MoveToContent() == XmlNodeType.Element)
{
using(XmlChunkReader chunkReader = new XmlChunkReader(r))
{
Item item = (Item)serializer.Deserialize(chunkReader);
Console.WriteLine(item.ToString());
}
}
r.ReadEndElement();
}
XmlChunkWriter can be created using XmlWriter. It can be used as a standalone XmlWriter, e.g., to perform serialization of objects. When XmlChunkWriter is closed, the main XmlWriter is ready to continue writing XML data. Using XmlChunkWriter helps format data in the same manner and avoids writing of XML declaration instructions in the middle of XML.
// write file
using (XmlTextWriter w = new XmlTextWriter(xmlfile, Encoding.UTF8))
{
w.Formatting = Formatting.Indented;
w.WriteStartElement("items");
using (XmlChunkWriter chunkWriter = new XmlChunkWriter(w))
serializer.Serialize(chunkWriter, new Item(1, "First"));
using (XmlChunkWriter chunkWriter = new XmlChunkWriter(w))
serializer.Serialize(chunkWriter, new Item(2, "Second"));
w.WriteEndElement();
}
The library also simplifies the implementation of the IXmlSerializable interface.
The source code can be easily adapted for .NET framework version 1.1.
| You must Sign In to use this message board. | ||||||||
|
||||||||
|
||||||||
|
||||||||
|
||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 8 Aug 2006 Editor: Smitha Vijayan |
Copyright 2006 by notmasteryet Everything else Copyright © CodeProject, 1999-2009 Web22 | Advertise on the Code Project |