2

Is there a way to convert an object to XML but each element contains an attribute (let's be like this xt:type="int").
I know I can do it manually using reflection and iterate properties and ....
I'm asking if there's a way to generate it using pre-made library or something.
What I'm doing now is:

XmlDocument doc = new XmlDocument();
XmlSerializer ser = new XmlSerializer(document.GetType());
string result = string.Empty;
using (MemoryStream memStm = new MemoryStream())
 {
   ser.Serialize(memStm, document);
   memStm.Position = 0;
   result = new StreamReader(memStm).ReadToEnd();
 }

Because later I need to read it back to an object. All this I want to do it programmatically, not using XSD tool.

Thanks

UPDATE 1:
What I want to get looks something like this:

<note>
   <propertyName1 xs:type="string">value1</to>
   <propertyName2 xs:type="int">10</to>
   <propertyName2 xs:type="datetime">04-06-2015 01:10:00</to>
</note>

The most important is the attribute xs:type.

Dabbas
  • 3,112
  • 7
  • 42
  • 75

1 Answers1

1

If you use System.XML.Linq, you can add an XAttribute with whatever you want in it.

Lets say you have a Personn P with string Name and int Age

XElement e = new XElement( "Personne" );
XElement age = new XElement("Age",Personne.Age);
age.add(new XAttribute("xs:type", typeOf(Personne.Age)));
e.Add(age);
XElement name = new XElement("Name",Personne.Name);
name.add(new XAttribute("xs:type", typeOf(Personne.Name)));
e.Add(name);`

You will receive as XML:

<Personne>
<Age type="int">(the age of the personne)</age>
<Name type="string">(he name of the personne)</Name>
<Personne>

with "automated" process:

XElement p = new XElement( "Personne" );

foreach(var property in Personn.GetType().GetProperties()) {
XElement e = new XElement(prop.Name, prop.GetValue(P, null));
e.Add(new XAttribute("xs:type", typeOf(Personne.prop)));
p.Add(e);
}

EDITED: added "xs:" as you need it

Benoit Gidon
  • 79
  • 10