XML Binding Development Guide : PART II Code Generation Examples : Chapter 6 complexContent Example : Accessing the Address
Accessing the Address
When you run the sample main, complexContent_main, the output shows a zip code and a complete XML document. This document is created by unmarshaling the input file complexContent.xml, changing a piece of data, and then marshaling the result to the output.
The beginning of the sample application is just like the previous examples:
 
int main()
{
ipo::PurchaseOrder po;
try {
std::ifstream istrm("po.xml");
std::stringstream buffer;
buffer << istrm.rdbuf();
std::string xmlContents(buffer.str());
po.unmarshal(xmlContents);
 
} catch (const rwsf::XmlParseException &e) {
...
} catch (const rwsf::Exception &x) {
...
}
Next the sample application manipulates the billTo element, which as we know can be either a USAddress or a UKAddress. In the code below, the retrieval of the billTo address returns an rwsf::XmlBindingHandle, but we do not know its actual type. To find out, we call getTypeId() on the billTo object, which returns the value of the xsi:type attribute of the billTo element in the instance document. Based on this value, we can determine the actual type of billTo and produce the output appropriately.
 
rwsf::XmlBindingHandle billTo = po.getBillTo(); //1
 
// check address type. If UK address print post code;
// otherwise print zip code.
 
if (billTo.getTypeId() == "ipo::UKAddress") { //2
std::cout << "Post code = "
<< ((ipo::UKAddress&)billTo).getPostcode() << std::endl;
} else {
std::cout << "Zip code = "
<< ((ipo::USAddress&)billTo).getZip() << std::endl;
}
//1 Returns a rwsf::XmlBindingHandle which contains an Address, but whether a USAddress or a UKAddress is unknown.
//2 Uses getTypeId() method to determine the actual type and creates appropriate output based on the result.
Next the example code changes the shipTo address to be the same as the billTo address, and writes out the modified document.
 
po.setShipTo(po.getBillTo()); //1
 
rwsf::XmlStringWriter writer; //2
writer.setIgnoreWhitespace(false);
 
po.marshal(writer); //3
std::cout << writer.getString() << std::endl; //4
//1 Sets the shipTo address to be the same as the billTo address.
//2 Instantiates a writer and sets it to preserve whitespace.
//3 Calls the marshal() method that marshals the data to a supplied writer.
//4 Writes out the XML document.