September 2, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Working with XML in Managed C++

  • August 23, 2002
  • By Kate Gregory
  • Send Email »
  • More Articles »

Where does XML fit in .NET?

Throughout .NET you'll see places where XML belongs. For example, any class can serialize itself to and from XML if you just add the Serializable attribute to it when you declare it.

Here's a sample class that you might want to dump out as XML, or fill from XML:

[Serializable]
public __gc class PurchaseOrder
{
public:
  int customer;
  // other elements to be added
  PurchaseOrder(int id) {customer=id;}
  PurchaseOrder() {customer=0;}
};

You mark the class with the Serializable element. Only public variables can be serialized like this, and the class must have a default constructor. Once you've complied with those restrictions, life gets pretty simple. Here's how to dump out the object to a file:

PurchaseOrder* po = 
   new PurchaseOrder(Int32::Parse(xmlDoc->
     GetElementsByTagName("Customer")->Item(0)->
              Attributes->GetNamedItem("id")->get_Value()));
System::Xml::Serialization::XmlSerializer* ser =
   new System::Xml::Serialization::XmlSerializer(po->GetType());
System::IO::TextWriter* writer = 
       new System::IO::StreamWriter("po.xml");
ser->Serialize(writer,po);
writer->Close();

This would be a lot more readable if you used namespaces, but I wanted you to see the full namespaces associated with the classes I'm using here. The first line, which is very long, roots through the XML document looking for Customer tags, grabs the first one, looks for an attribute called id, and passes its value to the constructor for PurchaseOrder. Then I create a serializer and a writer, and called the Serialize() method of the serializer. The po.xml file comes out like this:

<?xml version="1.0" encoding="utf-8" ?> 
<PurchaseOrder xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <customer>123</customer> 
  </PurchaseOrder>

If PurchaseOrder was a large and complex class, perhaps using one of the .NET collection classes to hold a collection of items, I would still need just this little block of code to write it out as XML: make a serializer and a writer, then call Serialize(). To rehydrate objects from XML, you just do the same work in reverse:

PurchaseOrder* po2 = new PurchaseOrder();
ser = new System::Xml::Serialization::XmlSerializer(po2->GetType());
System::IO::FileStream* fs = 
     new System::IO::FileStream("po.xml", 
                                System::IO::FileMode::Open);
po2 = (PurchaseOrder*) ser->Deserialize(fs);
System::Console::WriteLine("Rehydrated customer is {0}.",
                           __box(po2->customer));

If you're using DataGrids in either ASP.NET or Windows applications, you can load them from a file of XML (wonderful for quick prototypes) or as part of your debugging, have them dump themselves out to XML when you need to. Just make an empty DataSet object, call its ReadXml method to fill it with XML from a file, then make it the data source for your DataGrid and call DataBind(). Or grab the XML from the DataGrid like this:

xmlstring = DataGrid1->DataSource->GetXml();

There's so much more you can do with XML using the .NET class libraries. In just a line or two, you can generate XML, transform from one layout to another, or find subsets of a document. With the schema support in Visual Studio you can generate a schema that matches a sample XML file, or edit XML with Intellisense that knows the schema you're using and reminds you what elements or attributes are allowed where you're typing. XML is at the heart of the .NET revolution, so you should see what it's all about sooner rather than later.

About the Author

Kate Gregory is a founding partner of Gregory Consulting Limited (www.gregcons.com). In January 2002, she was appointed MSDN Regional Director for Toronto, Canada. Her experience with C++ stretches back to before Visual C++ existed. She is a well-known speaker and lecturer at colleges and Microsoft events on subjects such as .NET, Visual Studio, XML, UML, C++, Java, and the Internet. Kate and her colleagues at Gregory Consulting specialize in combining software develoment with Web site development to create active sites. They build quality custom and off-the-shelf software components for Web pages and other applications. Kate is the author of numerous books for Que, including Special Edition Using Visual C++ .NET.

# # #





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel