Class properties into XML tags

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

Guest

Can someone point me in the right direction? I need to wrap some class
properties into XML tags in C#. I just need the XML tags and not the XML
document information.


Thanks.
 
Someone else chime in if I am pointing him in the wrong direction,

from what your describing it sounds like reflection is what you need to
use.
 
I'm rather new to reflection, and it is a pretty big namespace. Any idea how
I would accomplish this?

Thanks
 
You know, after reading some about reflection I realized I might have worded
my initial question wrong. I appologize, but this is basically what I need
(and after some thinking I might just do this with a stringbuilder).

I need to take the values of my class (let's say it's a person class with
properties like FirstName, LastName, Address, City, State, ZIP, etc..) and I
need to wrap these in XML tags like
<Person><FirstName></FirstName><LastName></LastName><Address></Address>.....</Person>.

I wan't sure if there was a quick way to do this with the built in XML
features, like a ToXML() method.

Sorry for the confusion.
 
Are you pulling the data from a database?

If so, alot of databases allow you to select "AS XML". SQL Server in
peticular has alot of XML based features.

You can tell SQL to selected specific records and return it in xml
format with the results wrapped like you described.

If the data is within your objects and not SQL, you would make a blank
xml file, like you did below, and then hydrate the xml file with data.

if you need some sample code, take a look System.Xml namespace for
methods to perform this. Sorry i dont know any off hand, it has been
awhile since I had to do anything like that.
 
Thanks Sean. After more reading, I think I could use customized serialization
to do what I need (although it might actually be easier to use a string
builder and manually build the tags).

Thanks for your replies.

Cheers.
 
mn_ms_user said:
Thanks Sean. After more reading, I think I could use customized serialization
to do what I need (although it might actually be easier to use a string
builder and manually build the tags).

You just need to make your class Serializable and use the XmlElement
and XmlAttribute attributes to control how each property if serialized.


using System.Xml.Serialization;

[Serializable]
public class MyClass
{
private int _ id;
private string _firstName;

[XmlElement("FirstName")]
public string FirstName
{
//property code here
}

[XmlAttribute("Id")]
public int Id
{
//property code here
}
}
 
Back
Top