xml storage of object state
Post on 05-Apr-2018
223 Views
Preview:
TRANSCRIPT
-
7/31/2019 XML Storage of Object State
1/32
Mobile Development
Storing State with XML
RobMilesDepartment of Computer Science
-
7/31/2019 XML Storage of Object State
2/32
Introduction
An introduction to the problem
Writing an XML file> The XMLTextWriter class> Attributes and Elements in XML
> Text Encoding in XML files
Reading an XML document
> The XMLDocument class XML and namespaces
Storing the XML on a Smartphone/PocketPC
-
7/31/2019 XML Storage of Object State
3/32
Storing High Score Data
I wanted to store the high score of a player in
a Smartphone game> Name of the player
> Name of the game
> Score reached in the game
The data may need to be exported and used
in other systems, for example league tables
XML is the obvious choice for this
-
7/31/2019 XML Storage of Object State
4/32
Writing a PC Version
Unless you use some ofthe Mobile Powertoys it is
hard to see what aSmartphone application isdoing
I therefore decided to write
a PC version of the code I can port the important
bits later
-
7/31/2019 XML Storage of Object State
5/32
XML Namespaces
To get direct access to the XML methods and
the text encoding types I have to use two
namespaces:using System.Xml;
using System.Text; Once I have these I can write a method to
save the values in an XML document
-
7/31/2019 XML Storage of Object State
6/32
Writing an XML document
publicvoid SaveXML ( string filename )
{
XmlTextWriter writer ;
writer = new XmlTextWriter( filename, Encoding.ASCII);writer.Formatting = Formatting.Indented ;
writer.WriteStartDocument();
writer.WriteStartElement("highscore");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
}
document with an empty highscore element
-
7/31/2019 XML Storage of Object State
7/32
Empty XML Document
The header of the document simply describes the
version of xml and the encoding being used
The score element is shown as empty
This is a completely legal XML document> but it does not contain any data.
-
7/31/2019 XML Storage of Object State
8/32
XML Attributes and Elements
There are two types of information in an XML file> Element: a lump of data about something; may contain other
elements
> Attribute: used to further describe a particular element.
The document being created presently has one
element, called highscore.
I can add an attribute to the highscore element which
identifies the game the score is for
-
7/31/2019 XML Storage of Object State
9/32
Adding an Attribute
publicvoid SaveXML ( string filename )
{
XmlTextWriter writer ;
writer = new XmlTextWriter (filename,Encoding.ASCII);writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("highscore");
writer.WriteAttributeString( "game", "Breakout");
writer.WriteEndElement();
writer.WriteEndDocument();writer.Close();
}
-
7/31/2019 XML Storage of Object State
10/32
Elements and Attribute Output
The game attribute identifies the name of the game
for which the high score was reached
This attribute is attributed to a given highscore
element
-
7/31/2019 XML Storage of Object State
11/32
Adding the Player and Score
Now we need to add the data about the player
and the score reached
There are two ways to do this:> add two more attributes to the highscore element. These
would be called playerand score and would hold the required
values.
> add two new elements, playerand score inside the highscoreelement
-
7/31/2019 XML Storage of Object State
12/32
Elements vs. Attributes
I have decided that player and score should be elements ratherthan attributes
It is easier for me to extend the player and score storage;
> I could add the address of the player and the date and time the score wasachieved
> Those attributes should bind to the player and score items, not the highscoreitself
Information directly about the high score data, such as the gameit applies to, should be an attribute
Another use for an attribute would be as an id tag of an element,or perhaps a version number (which you can see in the headerof the XML file itself)
-
7/31/2019 XML Storage of Object State
13/32
Writing the High Score
XmlTextWriter writer;
writer = new XmlTextWriter( filename, Encoding.ASCII) ;
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("highscore");
writer.WriteAttributeString( "game", "Breakout");
writer.WriteElementString("playername",playerName);
writer.WriteElementString("score", score.ToString());
writer.WriteEndElement();
writer.WriteEndDocument();writer.Close();
-
7/31/2019 XML Storage of Object State
14/32
High Score XML
Rob Miles
1500
-
7/31/2019 XML Storage of Object State
15/32
XML & Meanings
Before we read the XML it is important to
have discussion about the meaning of things
The program that we write will ascribe
meaning to the elements it gets:>A score which is a big value is good
> In golf this would not be true..
There is nothing in the XML which gives the
meaning of the data itself
-
7/31/2019 XML Storage of Object State
16/32
Element Namespace
Not to be confused with the C# namespace
(although the intention is similar)
Allows an element to state the context in
which this element has meaning
This means that two programmers using the
same name for an element could ensure thatpeople using their elements can determine
the proper context/ontology
-
7/31/2019 XML Storage of Object State
17/32
Adding a Namespace
writer.WriteStartElement("highscore",
"www.mygameuri.com/highscore");
The uri gives the user of this element aunique identifier for this element
This ensures that my highscore element can
be identified as unique There does not have to be a web page at the
uri
-
7/31/2019 XML Storage of Object State
18/32
The Namespace in XML
The xmlns attribute identifies the namespace
for this element
I can create a set of namespaces based at a
particular uri We will see how these are tested later on
-
7/31/2019 XML Storage of Object State
19/32
Reading XML
We are going to use the XmlDocument class
provided by .NET:
// get a new document
document =new XmlDocument();
// load it from a file
document.Load(filename);
We can then read properties off the documentto get at the data
-
7/31/2019 XML Storage of Object State
20/32
XmlDocument structure
Name : highscore
NamespaceURI: www.mygameuri.com/highscore
game: Breakout
playername score
Rob Miles 1234
-
7/31/2019 XML Storage of Object State
21/32
Getting the Root element
System.Xml.XmlElement rootElement =
document.DocumentElement;
// make sure it is the right elementif ( rootElement.Name != "highscore" )
{
Console.WriteLine ( "Wrong data" );
} This gets the root element for the document and
makes sure it is the right one
-
7/31/2019 XML Storage of Object State
22/32
Checking a namespace
// make sure it is in the right namespace
if ( rootElement.NamespaceURI !=
"www.mygameuri.com/highscore" )
{
Console.WriteLine ("Wrong namespace");
}
All elements have a namespace property which maps
on to the namespace attribute
-
7/31/2019 XML Storage of Object State
23/32
Reading an attribute
// check to see if the name is correct
string gameName =
rootElement.GetAttribute("game");if ( gameName != "Breakout" )
{
return false ;
} Attributes are accessed by their name using theGetAttribute method
-
7/31/2019 XML Storage of Object State
24/32
Getting a Child Element
The simplest way to get hold of a child element is to
use the name as an indexer:
XmlNode playerNameNode = rootElement["player"];if ( playerNameNode == null )
{
Console.WriterLine ( "Missing player name" );
}
This gets the element with the given name, or null if
the name is not found.
-
7/31/2019 XML Storage of Object State
25/32
Get the value of an element
The value of an element is a child of thatelement:
playerName = playerNameNode.FirstChild.Value; The FirstChild member of the element in
this case is the data payload of that element
We can set the player name to this
All the values are returned as strings This means that we need to parse the score
value to get an integer
-
7/31/2019 XML Storage of Object State
26/32
Setting Values
You can set values in an element as well
There is also a method call which will save an
element (and all of its children)
This can be used if you have updated values
in the document that you want to save
ou want
-
7/31/2019 XML Storage of Object State
27/32
File Storage
You need to decide where to store the XML
files themselves
The obvious place to put them is the samedirectory as the binary program
On the Compact Framework you need to do a
bit of work to get the location of this
-
7/31/2019 XML Storage of Object State
28/32
Getting the Current Directory
System.Reflection.Assembly execAssem =
System.Reflection.Assembly.GetExecutingAssembly();
// set up the application filename
// from the current assembly
string appFilePath =execAssem.GetModules()[0].FullyQualifiedName;
// now strip the path from this filename
applicationDirectory =
System.IO.Path.GetDirectoryName(appFilePath);
// make sure we have a path separator on the end
if (!applicationDirectory.EndsWith(@"\"))
{
applicationDirectory += @"\";
}
-
7/31/2019 XML Storage of Object State
29/32
Demo 01 Saving and Loading
Scores
This project runs on a Smartphone and saves
the score values which are entered by the
user It can also load them back
-
7/31/2019 XML Storage of Object State
30/32
XML and Data
XML data elements always end up as text
If you want to store text which may contain
things like < and > you will have to investigateCDATA which lets you write strings containing
arbitrary text
You must also perform parsing to recover anynumeric values which you have stored> Remember to handle errors!
-
7/31/2019 XML Storage of Object State
31/32
XML and Programs
The XMLDocument is a very good way to hold
a structure in memory
But if you simply want to read object statesyou may decide instead to just read through
the XML elements and pull out the properties
you want
-
7/31/2019 XML Storage of Object State
32/32
XML is Fun!
No, really..
It provides a very easy way to manage
program data in a flexible and extensiblemanner
> For very little effort on your part
Whenever you are storing program data, and
you arent putting it in a database, you should
put it in XML!
top related