Using Xml Dom to store and retrieve product selection

The .NET Compact Framework provides a set of classes that allow you to manipulate XML. These classes are contained in the System.xml namespace. The XMLDocument class is the first class you need to get familiar with. It provides the methods to create new XML elements and attributes.

In the Get() method of the Datasource property shown in the following snippet, we loop through all ListView items and for those items that are checked, create a new XML element to store the corresponding Product Code. For example, if the user ticked two products from the checklist, you will end up with the following XML:

<Product ProductCode='C01' /> <Product ProductCode='C02' /> </Root>

The code snippet to achieve the above is shown as follows:

public string Datasource {

XmlElement _xmlProduct; string _productCode; XmlTextWriter _xmlWriter; StringWriter _stringWriter; int _counter;

//Loop through the ListView items and create the //corresponding XML object

_xmlDoc = new XmlDocument();

_xmlRoot = _xmlDoc.CreateElement("Root");

_xmlDoc.AppendChild(_xmlRoot);

for (_counter = 0; _counter <= base.Items.Count - 1; _counter++)

_productCode = base.Items[_counter].Text; _xmlProduct = _xmlDoc.CreateElement("Product"); _xmlProduct.SetAttribute("ProductCode",

_productCode); _xmlRoot.AppendChild(_xmlProduct);

//Serialize the XML into a single string

_stringWriter = new StringWriter();

_xmlWriter = new XmlTextWriter(_stringWriter);

_xmlDoc.WriteTo(_xmlWriter);

_xmlWriter.Close();

_xmlWriter = null;

return _stringWriter.ToString();

int _counter; XmlElement _xmlProduct; string _productCode;

_Datasource = value;

//Rebuilds the XML object from a single string _xmlDoc = new XmlDocument(); _xmlDoc.LoadXml(_Datasource);

//Loops through each XML element and retrieves the //stored product codes. The MarkProduct() //method is called to place a tick next to each //corresponding ListView item

_xmlRoot = (XmlElement) (_xmlDoc.ChildNodes.Item(0)); for (_counter = 0; _counter <=

_xmlRoot.ChildNodes.Count - 1; _counter++)

_xmlProduct = (XmlElement)

(_xmlRoot.ChildNodes.Item(_counter)); _productCode =

_xmlProduct.GetAttribute("ProductCode"); MarkProduct(_productCode);

Was this article helpful?

0 0

Post a comment