2

I am currently trying to write a program in D that when called and passed an object, it will serialize the object into an XML document. I would like to make it as simple as passing the object into it, but I'm not entirely sure it can be done. Example:

class A
{
    //Constructors and fluff
    ....

    int firstInt;
    int secondInt;
}

.....
A myObj = new A();
XMLSerialize(myObj);

and the output would be

<A.A>
    <firstInt></firstInt>
    <secondInt></secondInt>
</A.A>

So, is it possible for me to even get the name of the variables inside of the object or would that have to all be manually done?

Daniel Martin
  • 570
  • 1
  • 9
  • 18

3 Answers3

6

Code is worth a thousand words (intentionally simplified):

import std.stdio;

void print(T)(T input)
    if (is(T == class) || is(T == struct))
{
    foreach (index, member; input.tupleof)
    {
        writefln("%s = %s", __traits(identifier, T.tupleof[index]), member);
    }
}

struct A
{
    int x, y;
}

void main()
{
    print(A(10, 20));
}
Mihails Strasuns
  • 3,783
  • 1
  • 18
  • 21
2

stingof is not the appropriate answer. There is some things in std.traits that do more of what you would expect. It is somewhat to do what you want generically, but you can use compile time reflections to generate serializers for whatever class you want.

https://github.com/msgpack/msgpack-d Does this.

Also:

https://github.com/Orvid/JSONSerialization/blob/master/JSONSerialization/std/serialization/xml.d

shammah
  • 86
  • 2
  • This answer was flagged as low-quality because of its length and content. Perhaps you can flesh it out a bit to make it more relevant to the OP and others. – crthompson Nov 28 '13 at 22:21
  • 1
    @paqogomez Is that some sort of automated action? This answer seems ok. Definitely not low-quality, just not the most useful answer. – eco Nov 29 '13 at 04:28
  • 1
    @eco It was flagged and I reviewed the flag. I thought it looked good too, but someone didnt. Just trying to help out the newer users. – crthompson Nov 29 '13 at 05:16
1

.stringof returns a string with the name of the variable.

void main()
{
    int some_int;
    assert(some_int.stringof == "some_int");
}
eco
  • 2,219
  • 15
  • 20
  • 2
    I recommend to use `__traits(identifier)` instead when just a symbol name is needed as stringof both does not work for functions and has unspecified text format. – Mihails Strasuns Nov 28 '13 at 22:15
  • I was going to flesh this out with some delicious traits but then I was distracted with wrapping up my thanksgiving dinner. Your answer is better. – eco Nov 29 '13 at 04:29