473,395 Members | 1,823 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

How to write XML with any name and type?

Disappointed, this is not the first time I'm posting this kind of a request
for help, but no helpful answer was posted yet.

I'll try make my question as clear as I can:

(1) I wish to write an XML file. this file will contain any number of
parameters to be used in my C# code as database.
(2) This file may contain any number of parameters, and I will know the
number of the parameters only at run time.
(3) Any parameter must have a name, but this name may be any name, and I
will know the names of the parameters only at run time.
(4) Any parameter must have a type, this type can be of any well known type
(int, string, float, dateTime, byte etc.), and I will know these types only
at run time.
(5) Any parameter may or may not have several more attributes
(authorization, precision, range), I will now if any of this attributes exist
only at run time.
(6) Any parameter will have a value of the type as described above.

I need to read this parameters form the XML file as their real value without
doing any code switching, and to assign these values to my run time data
members.

I thought I'll be able to load the XML file into DataSet and read the
parameters from it. But I'll be happy to use any other solution you may have.

---------
Thanks
Sharon
Oct 30 '06 #1
6 1332
One option would be to:

1. Create a class that implements the ISerializable interface
2. Serialize the class to XML (sample code below)
3. Deserialize the class from the XML back into a class (no code sample
on that one - sorry)

Sample Code

using System.Xml.Serialization;
using System.IO;

protected string SerializeObjectToString(object data)
{
if (data == null)
return string.Empty;

if (data.GetType().Name == "String")
return (string)data;
else
{
XmlSerializer mySerializer = new
XmlSerializer(data.GetType());

StringWriter myWriter = new StringWriter();
mySerializer.Serialize(myWriter, data);
string ret = myWriter.ToString();

myWriter.Close();

return ret;
}
}

Bill

Oct 30 '06 #2
One option would be to:

1. Create a class that implements the ISerializable interface
2. Serialize the class to XML (sample code below)
3. Deserialize the class from the XML back into a class (no code sample
on that one - sorry)

Sample Code

using System.Xml.Serialization;
using System.IO;

protected string SerializeObjectToString(object data)
{
if (data == null)
return string.Empty;

if (data.GetType().Name == "String")
return (string)data;
else
{
XmlSerializer mySerializer = new
XmlSerializer(data.GetType());

StringWriter myWriter = new StringWriter();
mySerializer.Serialize(myWriter, data);
string ret = myWriter.ToString();

myWriter.Close();

return ret;
}
}

Bill

Oct 30 '06 #3
Thanks Bill for you replay.

I'm not sure I understand how the serialization and deserialization can
solve my problem.

The XML file may contain any tree structure the user wishes, and I will now
this tree on at run time.

So, at run time, I need to reed the entire parameters from the XML, and
while reading I need to reed the parameters value without doing any code
switching and casting. I want to read the value in the correct type.

Can you please explain if and how your suggestion of serialize and
deserialize can do all of that?
---------
Thanks
Sharon
Nov 1 '06 #4
Do you know the full list of possible parameters up front? If so, you
could build a serializable "parameters" class that contains a value for
all of the parameters. As you read the XML you could populate the
appropriate parameter (and have it strongly-typed).

i.e.

[ISerializable]
public class MyParameters
{
public int Property1 { get; set; }

public string Property2 {get; set; }
}

If you don't know the full list of possible parameters beforehand, how
are you validating the incoming XML - is there an XSD? If so, you
could use the xsd.exe included in the .NET tools to create a class for
that schema that can directly read in the XML. This would allow you to
manipulate the XML in code. For more info see:
http://msdn.microsoft.com/library/de...toolxsdexe.asp.

Bill

Nov 1 '06 #5
No, sorry, I do not know full list of possible parameters up front.

And I can not use XSD, because the the XSD schema need to now beforehand the
tree structure and parameters names and types, which I do not. Only at run
time I now all of that.
--
Thanks
Sharon
Nov 1 '06 #6
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});
}
}

------
Regards
Sharon
Nov 2 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Bill Cohagan | last post by:
I'm writing a console app in c# and am encountering a strange problem. I'm trying to use redirection of the standard input stream to read input from a (xml) file. The following code snippet is from...
8
by: Jack | last post by:
Hi, Here is my problem: I am logging in to a page, where the page retrieves a record from a database. The text boxes are used in the display formto let the users update the fields, if they...
8
by: Arvind P Rangan | last post by:
Hi, i like to read an existing xml file which has a schema defined to it, and then write or add data to the existing xml file using vb.net/c#. May be this Question has been answered earlier....
0
by: DC | last post by:
The problem I'm using the .NET GridView and FormView objects for the first time and im getting the error "An OleDbParameter with ParameterName '@ID' is not contained by this...
0
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted...
3
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted...
0
by: =?Utf-8?B?YW5rMmdv?= | last post by:
Hi, Thanks in advance for reading this. Not sure where to post this question, but I hope someone in here can help. Trying to write to Event Log in VS 2005 (.NET 2.0) using Enterprise Library...
1
by: anupamaavadutha | last post by:
hi all, iam new to javascript. i have problem calling javascript functions.iam designing a calender page.here is my code. <%@ page...
3
by: mturner64 | last post by:
I am using Microsoft VWD 2008 express edition. I have linked an Access 2007 database to my asp.net application using a gridview control. On the webpage are four text boxes allowing a user to input...
5
by: satyabhaskar | last post by:
hi all, In my web page i have created radio buttons dynamically on to the page .....following is my code string Course, Semester, Section; int rowsCount; string con =...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.