How to indicate an XML element variable type?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I need to write an XML document, that other users can work with to change
values and to add elements.

My problem is that for each element that me or any other user will add,
should have some kind of attribute (or any other solution...) to indicate its
type, this type is a variable type to be used in my code (Int32, double,
byte, string etc.).
I need it so when I'm reading the XML by code (DOM parser), I will be able
to know the type of the variable that I have just read from the XML file.
I don't know a way to do it without an XSD file. But I can not use XSD
because it will prevent me to add new elements to the XML of the type I
wishes as it is not present in the XSD.

Does anyone now how to do so?
 
Ok, I think I found a way to do thanks to Marc Clifton articale on
CodeProject (http://www.codeproject.com/dotnet/MycroXaml.asp).

The XML file can be somthing like that:

<?xml version="1.0" encoding="utf-8"?>
<System Name="System">
<Paramaters>
<Speed type="System.Iint32">111</Speed >
<_xAxis type="System.Single">222</_xAxis>
<_yAxis type="System.Double">333</_yAxis>
<_ID type="System.Int64">444</_ID>
<_Name type="System.String">String value...</_Name>
</Paramaters>
</System>


And the C# code can be:

System.IO.StreamReader sr = new System.IO.StreamReader("TypesDef.xml");
string text = sr.ReadToEnd();
sr.Close();
XmlDocument doc = new XmlDocument();
doc.LoadXml(text);
XmlNode node = doc.FirstChild;
while( node.NodeType.ToString() != "Element" )
{
node = node.NextSibling;
}

XmlNode paramsNode = doc.SelectSingleNode("//Paramaters");
XmlNodeList nodeList = paramsNode.ChildNodes;
Hashtable verTypes = new Hashtable(nodeList.Count);
string typeName = "";
Type type;

foreach( XmlNode xmlNode in nodeList )
{
XmlAttribute attr = xmlNode.Attributes["type"];
typeName = attr.Value;
if( typeName == "System.String" )
{
verTypes[xmlNode.Name] = xmlNode.InnerText;
}
else
{
type = Type.GetType(typeName, false);
object typeIntance = Activator.CreateInstance(type);
System.Reflection.MethodInfo Parse = type.GetMethod("Parse", new Type
[] {typeof(String)});
verTypes[xmlNode.Name] = Parse.Invoke(type, new object[]
{xmlNode.InnerText});
}
}
 
Back
Top