Monday, February 18, 2008

How to read and write simple XML with Silverlight 1.1

Silverlight does not have access to XmlDocument so we must make use of the XmlReader and XmlWriter.

To write:

/// <summary>
/// Write data to XML in Silverlight 1.1
/// </summary>
/// <returns>string in XML format</returns>public string WriteXML()
{
StringBuilder sbuilder = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sbuilder);//create an XMLWriter from a StringBuilder
writer.WriteStartDocument();//start xml document tag

//<outerElement>
writer.WriteStartElement("outerElement");

//<innerElement>
writer.WriteStartElement("innerElement");

//<attribute1> of inner element
writer.WriteStartAttribute("attribute1");
writer.WriteString("value of attribute1");
writer.WriteEndAttribute();

//<attribute2> of inner element
writer.WriteStartAttribute("attribute2");
writer.WriteString("value of attribute2");
writer.WriteEndAttribute();

//</innerElement>
writer.WriteEndElement();

//</outerElement>
writer.WriteEndElement();

writer.WriteEndDocument();//end xml document tag
writer.Flush();

return sbuilder.ToString();
}

This will output:

<?xml version="1.0" encoding="utf-16"?>
<outerElement>
<innerElement attribute1="value of attribute1" attribute2="value of attribute2" />
</outerElement>

To read:

/// <summary>
/// Read data from XML in Silverlight 1.1
/// </summary>
/// <param name="xmlString">string in XML form to read</param>
public void ReadXML(string xmlString)
{
TextReader stream = new StringReader(xmlString);
XmlReader reader = XmlReader.Create(stream);//create an XML reader
bool hasMore = reader.Read();
while (hasMore)//read till we get to the end
{
//lets just find the inner element and read its attributes
if (reader.IsStartElement() && reader.Name == "innerElement")
{
string at1 = reader.GetAttribute("attribute1");
string at2 = reader.GetAttribute("attribute2");
//todo: do something with the attributes...
}
//if we had other data, we would have logic for each value we wanted to read
hasMore = reader.Read();
}
}

ReadXML(WriteXML()); will read “value of attribute1” and “value of attribute2” (but do nothing with the data).

For readability I have used hard coded string values. For production code, you should define a schema of consts or an enumeration for all element names.

No comments: