How to indicate an XML element variable type?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sharon

    #1

    How to indicate an XML element variable type?

    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?


    --
    Thanks
    Sharon
  • Sharon

    #2
    RE: How to indicate an XML element variable type?

    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.Ii nt32">111</Speed >
    <_xAxis type="System.Si ngle">222</_xAxis>
    <_yAxis type="System.Do uble">333</_yAxis>
    <_ID type="System.In t64">444</_ID>
    <_Name type="System.St ring">String value...</_Name>
    </Paramaters>
    </System>


    And the C# code can be:

    System.IO.Strea mReader sr = new System.IO.Strea mReader("TypesD ef.xml");
    string text = sr.ReadToEnd();
    sr.Close();
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(tex t);
    XmlNode node = doc.FirstChild;
    while( node.NodeType.T oString() != "Element" )
    {
    node = node.NextSiblin g;
    }

    XmlNode paramsNode = doc.SelectSingl eNode("//Paramaters");
    XmlNodeList nodeList = paramsNode.Chil dNodes;
    Hashtable verTypes = new Hashtable(nodeL ist.Count);
    string typeName = "";
    Type type;

    foreach( XmlNode xmlNode in nodeList )
    {
    XmlAttribute attr = xmlNode.Attribu tes["type"];
    typeName = attr.Value;
    if( typeName == "System.Str ing" )
    {
    verTypes[xmlNode.Name] = xmlNode.InnerTe xt;
    }
    else
    {
    type = Type.GetType(ty peName, false);
    object typeIntance = Activator.Creat eInstance(type) ;
    System.Reflecti on.MethodInfo Parse = type.GetMethod( "Parse", new Type
    [] {typeof(String) });
    verTypes[xmlNode.Name] = Parse.Invoke(ty pe, new object[]
    {xmlNode.InnerT ext});
    }
    }

    ------
    Regards
    Sharon

    Comment

    Working...